2017-10-07 183 views
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 
     } 
    } 

我以毫秒爲單位獲取時間戳記服務器。什麼是正確的方法?

+0

對於起動器,你應該通過*秒*爲'日期(timeIntervalSince1970:)',不毫秒。 –

+0

@MartinR謝謝:)它的工作!你能解釋一下嗎? –

+1

只需閱讀文檔https://developer.apple.com/documentation/foundation/date/1780353-init:*「創建一個相對於1970年1月1日UTC時間00:00:00初始化的日期值,給定數量* *秒。**「* –

回答

0
let date1 = NSDate(timeIntervalSince1970: 1507211263)//Thursday, 5 October 2017 13:47:43 
let date2 = NSDate(timeIntervalSince1970: 1507556863)//Monday, 9 October 2017 13:47:43 

var secondsBetween: TimeInterval = date2.timeIntervalSince(date1 as Date) 
var numberOfDays = Int(secondsBetween/86400) 
print("There are \(numberOfDays) days in between the two dates.") 

//供參考:86400秒= 24小時

+0

請注意,某些日子有[閏秒](https://en.wikipedia.org/wiki/Leap_second),長度爲86401秒。因此,您的公式可能(儘管不太可能)給出錯誤的答案。 –

相關問題