繁体   English   中英

两个时间戳之间的天数

[英]Number of days between two timestamps

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

代码 :

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

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

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 小时

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM