ios 使用本地时区将 unix 时间戳转换为 NSdate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10922363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a unix timestamp to NSdate using local timezone
提问by Alexander of Norway
I'm getting some start_times
and end_times
in the form of NSDecimalNumber
s back from an API request.
我得到了一些start_times
和end_times
的形式NSDecimalNumber
期从API请求回。
I have successfully been able to convert these NSDecimalNumber
s into NSDate
s, but the code is not taking time zones into account.
我已经成功地将这些NSDecimalNumber
s 转换为NSDate
s,但是代码没有考虑时区。
I need for it to use the timezone that is default on the device.
我需要它使用设备上的默认时区。
回答by shabbirv
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];
回答by David R?nnqvist
Unix time doesn't have a time zone. it's defined in UTC as the number of seconds since midnight Jan 1 1970.
Unix 时间没有时区。它在 UTC 中定义为自 1970 年 1 月 1 日午夜以来的秒数。
You should get the NSDates in the correct time zone by using
您应该使用正确的时区获取 NSDates
[NSDate dateWithTimeIntervalSince1970:myEpochTimestamp];
回答by skram
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];