Ravindhiran
Ravindhiran

Reputation: 5384

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

Upvotes: 0

Views: 9443

Answers (2)

Sudheer Kolasani
Sudheer Kolasani

Reputation: 283

try this....

follow this for NSDateFormatter

NSString *dateStr = @"1477644628477";



double timestampComment = [dateStr doubleValue]/1000;

NSTimeInterval  timeInterval =timestampComment ;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy h:m:s a"];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];

NSString *formattedDateString = [dateFormatter stringFromDate:date];

NSLog(@"formattedDateString: %@", formattedDateString);

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

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

Upvotes: 14

Related Questions