Date日期的加減

通過(guò)Calendar實(shí)現(xiàn)日期加減。
主要是通過(guò)DateComponents組件設(shè)置要加減的年月日
下面舉幾個(gè)例子

  • 獲取上一天
extension Date {
    
    func kk_lastDay() -> Date? {
        //.gregorian代表公歷
        let calendar = Calendar(identifier: .gregorian)
        
        var components = calendar.dateComponents([.year, .month, .day], from: self)
        
        /*
         * value是int型,component對(duì)應(yīng)dateComponents(上一行代碼)設(shè)置,
         * 設(shè)置了year,month,day中的哪個(gè)就設(shè)置哪個(gè)
         * value負(fù)數(shù)代表向前推幾年,幾月,幾天,正數(shù)代表向后推幾年,幾月,幾天。按需設(shè)置
         */
        components.setValue(0, for: .year)
        components.setValue(0, for: .month)
        components.setValue(-1, for: .day)
        
        let lastDay = calendar.date(byAdding: components, to: self)
        
        return lastDay
    }
 }
  • 獲取下一個(gè)月(Components也可以只設(shè)置其中一個(gè),按需求來(lái))
    func kk_nextMonth() -> Date? {
        //.gregorian代表公歷
        let calendar = Calendar(identifier: .gregorian)
        
        var components = calendar.dateComponents([.month], from: self)
        
        /*
         * components只用了.month來(lái)生成,所以只設(shè)置month的值就好了
         * 這里是獲取下一個(gè)月,所以.month的value = 1,如果是上兩個(gè)個(gè)月value = -2
         */
        components.setValue(1, for: .month)
        
        let nextMonth = calendar.date(byAdding: components, to: self)
        
        return nextMonth
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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