How to convert long integer time to NSString or NSDate to display time?

I got the serial number of the Java Date form, which translates to a long-integer such as "1352101337000". The problem I am facing is how to parse this long integer back to NSDate or NSString so that I can understand what time the serial number is displayed.

Does anyone have a solution for this case?

+8
long-integer ios nsdate
source share
2 answers

Use it

NSTimeInterval timeInMiliseconds = [[NSDate date] timeIntervalSince1970]; 

To change it,

 NSDate* date = [NSDate dateWithTimeIntervalSince1970:timeInMiliseconds]; 

According to apple documentation,

NSTimeInterval: Used to indicate the time interval in seconds.

typedef double NSTimeInterval;

This is a double type.

To convert a date to a 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]; 
+8
source share

Swift

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

Follow these 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 correct before simply converting any old integer to a date using the method above. If you convert the time interval in seconds , then do not divide by 1000, of course.
  • There are other ways to convert and display strings. See this more complete explanation .
+2
source share

All Articles