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

时间:2012-06-06 21:11:36

标签: iphone ios objective-c nsdate

我从API请求中以start_times的形式获得了一些end_timesNSDecimalNumber

我已成功将这些NSDecimalNumber转换为NSDate s,但代码未考虑时区。

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

3 个答案:

答案 0 :(得分:30)

这应该使用当前区域设置

执行您需要的操作
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];

答案 1 :(得分:9)

Unix时间doesn't have a time zone。它在UTC中定义为自1970年1月1日午夜以来的秒数。

您应该使用

在正确的时区内获取NSDates
[NSDate dateWithTimeIntervalSince1970:myEpochTimestamp];

答案 2 :(得分: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];
相关问题