NSDate timeIntervalSince1970 not working in Swift?

北战南征 提交于 2019-11-26 12:19:59

问题


I am doing this in swift:

let date = NSDate(timeIntervalSince1970: 1432233446145.0)
println(\"date is \\(date)\")

The log gives me this:

 date is 47355-09-02 23:55:45 +0000

Then I try to get an interval back out just for testing:

let tI = expirationDate.timeIntervalSinceDate(date)
println(\"tI = \\(tI)\")

I get:

tI = 0.0

What am I doing wrong? I can seem to make the timeIntervalSince1970 call work properly. Is there any known issued with that in Swift, or am I missing something here?


回答1:


1432233446145 most probably is a time interval given in milliseconds:

let date = NSDate(timeIntervalSince1970: 1432233446145.0/1000.0)
print("date is \(date)")
// date is 2015-05-21 18:37:26 +0000

Swift 3 and later:

let date = Date(timeIntervalSince1970: 1432233446145.0/1000.0)



回答2:


I think your timestamp is incorrect. This results in your date being september 2nd, 47355.

If I use the following I get the date for (right about) now:

let date = NSDate(timeIntervalSince1970: 1431024488)
println("date is \(date)")
// "date is 2015-05-07 18:48:08 +0000"

The printed date is not a localized timestamp, so you'll have to do some localization of your own I suppose. An example:

let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
println("formatted date is \(formatter.stringFromDate(date))")
// "formatted date is 07-05-2015 20:48:08"

And for completeness I also checked with an expiration date that's 1100 seconds larger than the initial date:

let expirationDate = NSDate(timeIntervalSince1970: 1431025588)
let diff = expirationDate.timeIntervalSinceDate(date)
println("expires in: \(diff)")
// "expires in: 1100.0"

So, the timeIntervalSince1970 seems to work fine, I think your interval was just not what you wanted it to be.




回答3:


From your code and the log content follows:

date.isEqual(expirationDate)

--> Your stuff has just expired :-).



来源:https://stackoverflow.com/questions/30109219/nsdate-timeintervalsince1970-not-working-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!