AlexanderN
AlexanderN

Reputation: 2670

Converting a unix timestamp to NSdate using local timezone

I'm getting some start_times and end_times in the form of NSDecimalNumbers back from an API request.

I have successfully been able to convert these NSDecimalNumbers into NSDates, but the code is not taking time zones into account.

I need for it to use the timezone that is default on the device.

Upvotes: 8

Views: 20479

Answers (3)

shabbirv
shabbirv

Reputation: 9098

This should do what you need with current locale

double unixTimeStamp =1304245000;
NSTimeInterval _interval=unixTimeStamp;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setDateFormat:@"dd.MM.yyyy"];
NSString *dateString = [formatter stringFromDate:date];

Upvotes: 31

skram
skram

Reputation: 5314

Try something like this..

NSDate* sourceDate = ... // your NSDate

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];

Upvotes: 8

David Rönnqvist
David Rönnqvist

Reputation: 56625

Unix time doesn't have a time zone. it's defined in UTC as the number of seconds since midnight Jan 1 1970.

You should get the NSDates in the correct time zone by using

[NSDate dateWithTimeIntervalSince1970:myEpochTimestamp];

Upvotes: 9

Related Questions