简体   繁体   中英

Converting a unix timestamp to NSdate using local timezone

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

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

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

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];

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];

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM