8

I got a serial number form Java Date which convert into long-integer such as "1352101337000". The problem I met is how to analyze this long-integer number back to NSDate or NSString so that I can clear to know what time the serial number is displaying.

Do anybody have solution for this case?

Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
Lothario
  • 300
  • 1
  • 5
  • 10

2 Answers2

8

Use this,

NSTimeInterval timeInMiliseconds = [[NSDate date] timeIntervalSince1970];

To change it back,

NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeInMiliseconds];

As per apple documentation,

NSTimeInterval: Used to specify a time interval, in seconds.

typedef double NSTimeInterval;

It is of type double.

To convert a date to string,

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];

//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];

[formatter release];
iDev
  • 23,310
  • 7
  • 60
  • 85
  • 2
    Also check if you need to add this: [NSDate dateWithTimeIntervalSince1970:(ms / 1000)]; – Pach Mar 12 '14 at 11:09
3

Swift

This answer has been updated for Swift 3, and thus no longer uses NSDate.

Do the following steps to convert a long integer to a date string.

// convert to seconds
let timeInMilliseconds = 1352101337001
let timeInSeconds = Double(timeInMilliseconds) / 1000

// get the Date
let dateTime = Date(timeIntervalSince1970: timeInSeconds)

// display the date and time
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long
print(formatter.string(from: dateTime)) // November 5, 2012 at 3:42:17 PM

Notes

  • Since Java dates are stored as long integers in milliseconds since 1970 this works. However, make sure this assumption is true before just converting any old integer to a date using the method above. If you are converting a time interval in seconds then don't divide by 1000, of course.
  • There are other ways to do the conversion and display the string. See this fuller explanation.
Community
  • 1
  • 1
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393