如何将1970年以来的NSTimeInterval转换为NSDate

时间:2013-06-28 12:45:13

标签: ios nsdate

这是我的代码

“时间间隔”= 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);

输出格式为DateString:45460-03-21 10:53:20

但我要求的输出是2013-06-28 04:26:29 America / Los_Angeles

2 个答案:

答案 0 :(得分:14)

您的间隔以毫秒表示,而dateWithTimeIntervalSince1970则需要以秒为单位表示的间隔。将数字除以1000得到正确的值:

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

答案 1 :(得分:0)

试试这个......

关注此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);