Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 dateWithTimeIntervalSince1970:epoch] description];

I got a wrong value...

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

Thanks

like image 823
Maxime Avatar asked Jul 11 '11 19:07

Maxime


2 Answers

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);
like image 50
Steve HHH Avatar answered Oct 07 '22 13:10

Steve HHH


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
like image 39
Tommy Avatar answered Oct 07 '22 13:10

Tommy