Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong value returned after formatting timestamp

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

like image 266
Striving Avatar asked Jul 09 '26 23:07

Striving


2 Answers

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.


enter image description here

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.

like image 103
nhgrif Avatar answered Jul 11 '26 23:07

nhgrif


You have to divide your timestampDouble by 1000 since the NSTimeInterval is in seconds and you are giving it in milliseconds.

like image 42
Pradeep K Avatar answered Jul 12 '26 01:07

Pradeep K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!