0
我想獲得兩個時間戳之間的天數,但使用此代碼時出現錯誤值。兩個時間戳之間的天數
代碼:
let currentDateTimeStamp = Date().timeIntervalSince1970 * 1000.0
let firstDate = Date.init(timeIntervalSince1970: currentDateTimeStamp)
let lastDate = Date.init(timeIntervalSince1970: individualCellData["joining_date"] as! TimeInterval)
// First Method using extension
let daysBetween = firstDate.interval(ofComponent: .day, fromDate: lastDate)
// Second method
let components = Calendar.current.dateComponents([.day], from: lastDate, to: firstDate)
extension Date {
func interval(ofComponent comp: Calendar.Component, fromDate date: Date) -> Int {
let currentCalendar = Calendar.current
guard let start = currentCalendar.ordinality(of: comp, in: .era, for: date) else { return 0 }
guard let end = currentCalendar.ordinality(of: comp, in: .era, for: self) else { return 0 }
return end - start
}
}
我以毫秒爲單位獲取時間戳記服務器。什麼是正確的方法?
對於起動器,你應該通過*秒*爲'日期(timeIntervalSince1970:)',不毫秒。 –
@MartinR謝謝:)它的工作!你能解釋一下嗎? –
只需閱讀文檔https://developer.apple.com/documentation/foundation/date/1780353-init:*「創建一個相對於1970年1月1日UTC時間00:00:00初始化的日期值,給定數量* *秒。**「* –