使用本地时区将unix时间戳转换为NSdate

Ale*_*way 8 iphone objective-c nsdate ios

我从API请求中得到一些start_timesend_timesNSDecimalNumbers 形式返回.

我已经成功地将这些NSDecimalNumbers转换为NSDates,但代码没有考虑时区.

我需要它使用设备上默认的时区.

sha*_*irv 31

这应该用当前的语言环境做你需要的

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];
Run Code Online (Sandbox Code Playgroud)


Dav*_*ist 9

Unix时间没有时区.它在UTC中定义为自1970年1月1日午夜以来的秒数.

您应该使用在正确的时区内获取NSDates

[NSDate dateWithTimeIntervalSince1970:myEpochTimestamp];
Run Code Online (Sandbox Code Playgroud)


skr*_*ram 7

试试这样的东西......

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];
Run Code Online (Sandbox Code Playgroud)