Ravindhiran Ravindhiran - 1 month ago 12
iOS Question

How to convert NSTimeInterval since1970 to NSDate

here is my code

"Time interval" = 1372418789000;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:1372418789000];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(@"formattedDateString: %@", formattedDateString);


The output is formattedDateString: 45460-03-21 10:53:20

But my required output is 2013-06-28 04:26:29 America/Los_Angeles

Answer

Your interval is expressed in milliseconds, while the dateWithTimeIntervalSince1970 expects an interval expressed in seconds. Divide the number by 1000 to get the right value:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:1372418789];
// Divided by 1000 (i.e. removed three trailing zeros) ^^^^^^^^
NSString *formattedDateString = [dateFormatter stringFromDate:date];
// Fri, 28 Jun 2013 11:26:29 GMT
NSLog(@"formattedDateString: %@", formattedDateString);
Comments