可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
how I can convert an epoch time value to NSDate. For example I use this value : 1310412600000. and I am in the EDT time zone.
When I try this :
NSString *bar = [[NSDate dateWithTimeIntervalSince1970:epoch] description];
I got a wrong value...
What is the good way? I spend a lot of time with that....
Thanks
回答1:
Epoch time (also known as "Unix" and "POSIX" time) is the number of seconds since the start of 1970. You can convert epoch time to NSDate with this algorithm:
- Instantiate NSDate object and pass the epoch time as a parameter to NSDate's initWithTimeIntervalSince1970 initializer. You're done. The NSDate object is set to the epoch time. NSDate stores times internally in the UTC time zone. It's up to you how it is displayed.
- [Optional] Format your NSDate to the appropriate time zone with an NSDateFormatter.
Here's the code I used:
// Sample string epochTime is number of seconds since 1970 NSString *epochTime = @"1316461149"; // 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);
回答2:
Per the documentation, dateWithTimeIntervalSince1970: runs from January 1, 1970, 00:00 GMT. So you should be getting results four hours later than those you really want.
Hence the simplest thing ― if you don't mind hard coding the offset from GMT to EDT ― would seem to be:
[[NSDate dateWithTimeIntervalSince1970:epoch] dateByAddingTimeInterval:-240] // or: [NSDate dateWithTimeIntervalSince1970:epoch - 240]
Though to eliminate arbitrary constants (and be a little cleaner), you probably want something like:
NSTimeZone *EDTTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"EDT"]; NSInteger secondsDifferenceFromGMT = [EDTTimeZone secondsFromGMTForDate:[NSDate dateWithTimeIntervalSince1970:0]]; NSDate *startOfEpoch = [NSDate dateWithTimeIntervalSince1970:secondsDifferenceFromGMT]; ... NSDate *newDate = [startOfEpoch dateByAddingTimeInterval:firstInterval]; // etc
回答3: