两个时间戳之间的天数

时间:2017-10-07 13:58:11

标签: ios swift unix-timestamp

我想获得两个时间戳之间的天数,但是使用此代码我得到了错误的值。

代码:

    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
        }
     }

我从服务器获取时间戳,以毫秒为单位。什么是正确的方法?

2 个答案:

答案 0 :(得分:1)

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.")

// FYI:86400秒= 24小时

答案 1 :(得分:0)

extension Date {
    func timeStampToDay(timeStampInMillisecond:Double) -> Int {
        let date = Date()
        let todaysDateStamp = date.timeIntervalSince1970
        let timeStampDate = Date(timeIntervalSince1970: timeStampInMillisecond / 1000)
        var secBetween = Date(timeIntervalSince1970: todaysDateStamp).timeIntervalSince(timeStampDate)
        return Int(abs(secBetween) / 86400)
    }
    func timeStampToDay(timeStampInSecond:Double) -> Int {
        let date = Date()
        let todaysDateStamp = date.timeIntervalSince1970
        let timeStampDate = Date(timeIntervalSince1970: timeStampInMillisecond)
        var secBetween = Date(timeIntervalSince1970: todaysDateStamp).timeIntervalSince(timeStampDate)
        return Int(abs(secBetween) / 86400)
    }
}