swift 計(jì)算兩個(gè)日期的時(shí)間差(年/月/日/時(shí)/秒)

let date1Str = "2016/09/30"
let date2Str = "2021/12/01"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
let date1 = dateFormatter.dateFromString(date1Str)
let date2 = dateFormatter.dateFromString(date2Str)

let calendar = NSCalendar.currentCalendar()
let unitFlags:NSCalendarUnit = [NSCalendarUnit.Year, NSCalendarUnit.Month , NSCalendarUnit.Day , NSCalendarUnit.Hour , NSCalendarUnit.Minute , NSCalendarUnit.Second]
let components = calendar.components(unitFlags, fromDate: date1!, toDate: date2!, options: NSCalendarOptions.init(rawValue: 0))

let timeDifference = "\(components.year)" + "年" + "\(components.month)" + "個(gè)月"
let timeDifferences = "兩個(gè)日期的時(shí)間差是:" + timeDifference + "\(components.day)" + "天"

print(components.hour)
print(components.second)

如果你只是想計(jì)算兩個(gè)月份的時(shí)間差
日期格式應(yīng)設(shè)置為 yyyy/MM
同理 年/時(shí)/秒 so easy

最后編輯于
?著作權(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)容