问题
I am trying to format a timestamp but the wrong value is returned.
let timestampDouble: Double = 1455970380471
let timestamp = NSDate(timeIntervalSince1970: timestampDouble)
let formattedTimestamp = NSDateFormatter.localizedStringFromDate(timestamp, dateStyle: .MediumStyle, timeStyle: .ShortStyle)
formattedTimestamp returns Jun 22, 48115, 8:49 AM
instead of the correct timestamp of Feb 20, 2016, 11:13 PM
(from epochconverter.com).
回答1:
You've got the wrong value.
I reversed the process, starting with the date string you want, and ran it through this code:
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .ShortStyle
let date = dateFormatter.dateFromString("Feb 20, 2016, 11:13 PM")
let timeInterval = date?.timeIntervalSince1970
In a Swift playground, timeInterval
has a value of 1456031580
which is three digits shorter than the value you're using.
When I go back to your original code and use this new value:
let timestampDouble: Double = 1456031580
let timestamp = NSDate(timeIntervalSince1970: timestampDouble)
let formattedTimestamp = NSDateFormatter.localizedStringFromDate(timestamp, dateStyle: .MediumStyle, timeStyle: .ShortStyle)
We get the expected value: "Feb 20, 2016, 11:13 PM"
.
Of course, note that the exact time interval you get (the 1456031580
number) from the first snippet and the exact string you get out for that particular number will depend on your time zone.
Once you linked to Epoch Converter, I pasted your original value in here and indeed got the correct value of February something-ish. But it's important to note the bolded text.
Assuming that this timestamp is in milliseconds:
The website sees the number would give you a date 46,000 years in the future and guesses that you've actually given it milliseconds, so it makes a calculation based on that assumption.
NSDate
's timeIntervalSince1970
constructor takes an argument of type NSTimeInterval
, which is always a measure of seconds, not milliseconds. You need to divide your original value by 1000 to get the number of seconds, or write an NSDate
constructor which expects to be initialized with the number of milliseconds since 1970 rather than the number of seconds, as the initializer you used expects.
回答2:
You have to divide your timestampDouble by 1000 since the NSTimeInterval is in seconds and you are giving it in milliseconds.
来源:https://stackoverflow.com/questions/35591351/wrong-value-returned-after-formatting-timestamp