简体   繁体   English

将时间戳转换为NSDate

[英]Convert Timestamp to NSDate

I have a double value timestamp 1477933200000.0 from a JSON, and I want to convert into NSDate then string . 我有一个来自JSON的double值时间戳记1477933200000.0,我想转换为NSDate然后是string This what I did, 这就是我所做的

let dateNow = NSDate(timeIntervalSinceNow: timestampDouble)
let date1970 = NSDate(timeIntervalSince1970: timestampDouble)
let dateRef = NSDate(timeIntervalSinceReferenceDate: timestampDouble)

let dateFormatter = NSDateFormatter()
// dateFormatter.dateFormat = "MM/dd/YYYY HH:MM:ss a"
dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle

let convDateNow = dateFormatter.stringFromDate(dateNow)
print("Date Now: \(convDateNow)")

let convDate1970 = dateFormatter.stringFromDate(date1970)
print("Date Now: \(convDate1970)")

let convRefDate = dateFormatter.stringFromDate(dateRef)
print("Date Now: \(convRefDate)")

I tried to convert it in http://www.epochconverter.com and it showed me the correct date. 我尝试将其转换为http://www.epochconverter.com ,它向我显示了正确的日期。 But all three type ( timeIntervalSinceNow , timeIntervalSince1970 , and timeIntervalSinceReferenceDate ) is weird. 但是所有这三种类型( timeIntervalSinceNowtimeIntervalSince1970timeIntervalSinceReferenceDate )都很奇怪。 This is the result from those type respectively. 这分别是这些类型的结果。

Date Now: September 2, 48850 at 5:50:04 PM
Date Now: November 3, 48803 at 3:00:00 PM
Date Now: November 3, 48834 at 3:00:00 PM

So what I am doing wrong here? 那么我在这里做错了吗? I just want to get the difference between date now and the date from json (timestamp). 我只是想得到现在的日期和json(时间戳)中的日期之间的差异。

Any help would be really appreciated. 任何帮助将非常感激。 Thank you! 谢谢!

Notice that when you use epochconverter.com, there is a message saying "Assuming that this timestamp is in milliseconds ". 请注意,当您使用epochconverter.com时,将显示一条消息“假设此时间戳以毫秒为单位 ”。

Now, try removing the three trailing zeroes (to the left of the decimal). 现在,尝试删除三个尾随零(在小数点左侧)。 It will now assume you're dealing with seconds and it will give you the same date & time. 现在,它将假定您正在处理秒,并且会给您相同的日期和时间。

In iOS, NSTimeInterval (or TimeInterval in Swift) is indeed typedef'd as a double (or Double), but it is interpreted as seconds (with sub-millisecond precision). 在iOS中,NSTimeInterval(或Swift中的TimeInterval)确实被类型定义为double(或Double),但它被解释为秒(精确到亚毫秒)。 Therefore, the various NSDate() constructor overloads are expecting the parameter to be expressed in seconds. 因此,各种NSDate()构造函数重载都期望参数以秒表示。

So you may need to divide that timestamp by 1000 to convert from milliseconds to seconds. 因此,您可能需要将该时间戳除以1000,才能将毫秒转换为秒。

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

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