2012-06-06 194 views
7

我从API请求返回和end_times,形式为NSDecimalNumber使用本地时区将unix时间戳转换为NSdate

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

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

+0

可能的副本[转换历史时间到可可/ iPhone中的NSDate](http://stackoverflow.com/q/2609561/608157) –

+0

另一个可能的副本是[将历元时间转换为具有良好时区的目标c的NSDate](http: //stackoverflow.com/q/6655446/608157) –

+1

有ot她也是......在提问前使用右上角的搜索字段。这是[“如何问”页面上的第一个话题](http://stackoverflow.com/questions/how-to-ask) –

回答

28

这应该做你需要与当前区域

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

Unix时间doesn't have a time zone什么。因为午夜1月1日1970年

它在UTC定义为秒数,您应该使用

[NSDate dateWithTimeIntervalSince1970:myEpochTimestamp]; 
+0

大卫你好,你的哪一个是正确的? – Hemang

+0

这两个答案在创建日期对象时都是一样的。其余的只是格式化。 –

+0

感谢您的回复,但我只关心这行''[formatter setLocale:[NSLocale currentLocale]];'输出可能会有所不同? – Hemang

7

尝试这样的事情得到正确的时区的NSDates ..

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