Swift Date判斷是否是今年,今天,昨天和判斷今天是周幾

直接上代碼

extension Date {
/**
 *  是否為今天
 */
func isToday() -> Bool{
    let calendar = Calendar.current
    let unit: Set<Calendar.Component> = [.day,.month,.year]
    let nowComps = calendar.dateComponents(unit, from: Date())
    let selfCmps = calendar.dateComponents(unit, from: self)
    
    return (selfCmps.year == nowComps.year) &&
    (selfCmps.month == nowComps.month) &&
    (selfCmps.day == nowComps.day)
    
}

/**
 *  是否為昨天
 */
func isYesterday() -> Bool {
    let calendar = Calendar.current
    let unit: Set<Calendar.Component> = [.day,.month,.year]
    let nowComps = calendar.dateComponents(unit, from: Date())
    let selfCmps = calendar.dateComponents(unit, from: self)
    if selfCmps.day == nil || nowComps.day == nil {
        return false
    }
    let count = nowComps.day! - selfCmps.day!
    return (selfCmps.year == nowComps.year) &&
        (selfCmps.month == nowComps.month) &&
        (count == 1)
}

///只有年月日的字符串
func dataWithYMD() -> String {
    let fmt = DateFormatter()
    fmt.dateFormat = "yyyy-MM-dd"
    let selfStr = fmt.string(from: self)
    let result = fmt.date(from: selfStr)!
    print(result)
    return selfStr
}

///獲取當(dāng)前年月日的時間戳
func timeIntervalWithYMDDate() -> TimeInterval {
    let fmt = DateFormatter()
    fmt.dateFormat = "yyyy-MM-dd"
    let selfStr = fmt.string(from: self)
    let result = fmt.date(from: selfStr)!
    return result.timeIntervalSinceReferenceDate + 24 * 60 * 60
}
/**
 *  是否為今年
 */
func isThisYear() -> Bool {
    let calendar = Calendar.current
    let nowCmps = calendar.dateComponents([.year], from: Date())
    let selfCmps = calendar.dateComponents([.year], from: self)
    let result = nowCmps.year == selfCmps.year
    return result
}
/**
 *  獲得與當(dāng)前時間的差距
 */
func deltaWithNow() -> DateComponents{
    let calendar = Calendar.current
    let cmps = calendar.dateComponents([.hour,.minute,.second], from: self, to: Date())
    return cmps
}

}

判斷今天是周幾

    let calendar = Calendar.current
    if let weekday = calendar.dateComponents([.weekday], from: Date()).weekday {
        //第一天是從星期天算起,weekday在 1~7之間
        print((weekday + 5) % 7)
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容