[英]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. 我从API请求中获得了NSDecimalNumber
形式的一些start_times
和end_times
。
I have successfully been able to convert these NSDecimalNumber
s into NSDate
s, but the code is not taking time zones into account. 我已经成功地将这些NSDecimalNumber
转换为NSDate
,但是代码没有考虑时区。
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 . Unix时间没有时区 。 it's defined in UTC as the number of seconds since midnight Jan 1 1970. 在UTC中将其定义为自1970年1月1日午夜以来的秒数。
You should get the NSDates in the correct time zone by using 您应该使用以下命令在正确的时区中获取NSDates
[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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.