开发者

Convert epoch time to NSDate with good timezone with Objective c

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 dateWithTimeIntervalSince1开发者_JAVA百科970:epoch] description];

I got a wrong value...

What is the good way? I spend a lot of time with that....

Thanks


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:

  1. 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.
  2. [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);


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


Are you passing the value in seconds?

The method accepts value in seconds , not milliseconds.

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜