2017-10-07 255 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秒。因此,您的公式可能(尽管不太可能)给出错误的答案。 –