在可可/ iPhone中将纪元时间转换为NSDate

时间:2010-04-09 17:32:21

标签: iphone cocoa nsdate

我有一个纪元时间的价值,如123456789,现在我想在cocoa框架中将其转换为NSDate。有人能告诉我吗?

感谢

2 个答案:

答案 0 :(得分:50)

Documentation是你的朋友!

NSDate* date = [NSDate dateWithTimeIntervalSince1970:123456789];

答案 1 :(得分:7)

由于这是一个很大的打击,将有所贡献。请注意,只需转换为NSDate即可将其置于UTC时区。然后,如果要将其显示给用户,则必须转换为您的时区,Convert epoch time to NSDate with good timezone with Objective c

// Convert NSString to NSTimeInterval
NSTimeInterval seconds = [epochTime doubleValue];

// (Step 1) Create NSDate object
NSDate *epochNSDate = [[NSDate alloc] initWithTimeIntervalSince1970:seconds];
NSLog (@"Epoch time %@ equates to UTC %@", epochTime, epochNSDate);

// (Step 2) Use NSDateFormatter to display epochNSDate in local time zone
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
NSLog (@"Epoch time %@ equates to %@", epochTime, [dateFormatter stringFromDate:epochNSDate]);

// (Just for interest) Display your current time zone
NSString *currentTimeZone = [[dateFormatter timeZone] abbreviation];
NSLog (@"(Your local time zone is: %@)", currentTimeZone);