2013-06-28 84 views
-1

這裏是我的代碼如何轉換NSTimeInterval自1970年至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); 

輸出formattedDateString:45460-03-21 10點53分20秒

但我需要輸出爲2013年6月28日四點26分29秒美國/洛杉磯

回答

13

您的間隔以毫秒錶示,而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); 
+2

感謝,現在它的正常工作...... – Ravindhiran

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); 
相關問題