繁体   English   中英

将日期转换为设备时区

[英]Convert date to device timezone

我正在从服务器解析JSON,其中一个值是这样的日期: 2013-01-21 18:22:35 +00000

我的问题是如何将此日期转换为当地时间,例如2013-01-21 12:22:35 -0600

我需要将日期转换为其他格式吗?

谢谢!

编辑。

使用@Gabriele Petronella解决方案:

NSString * yourJSONString = @"2013-01-21 18:22:35 +0000";

NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
NSString* localAbbreviation = [localTimeZone abbreviation];

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:@"yyyy-MM-dd H:mm:ss Z"];
NSDate *aDate = [dateFormatter dateFromString:yourJSONString];

NSTimeZone *timezone = [NSTimeZone timeZoneWithName:localAbbreviation];
[dateFormatter setTimeZone:timezone];

NSLog(@"%@", [dateFormatter stringFromDate:aDate]);

一切正常!

您可以使用NSDateFormatterNSString读取日期,然后可以使用另一个(可能是相同的) NSDateFormatter显示更改时区的日期。

NSString * yourJSONString = @"2013-01-21 18:22:35 +0000";
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle
 ];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];    
NSDate * aDate = [dateFormatter dateFromString:yourJSONString];

NSTimeZone * timezone = [NSTimeZone timeZoneWithName:@"America/Chicago"];
[dateFormatter setTimeZone:timezone];

NSLog(@"%@", [dateFormatter stringFromDate:aDate);

请注意,时区只是显示的问题 ,而NSDate对象只是表示日期的抽象,它不受显示的影响。

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 
NSTimeZone *timeZone = [NSTimeZone localTimeZone]; [dateFormatter setTimeZone:timeZone];

NSString *myCurrentDeviceDate = [dateFormatter stringFromDate:[NSDate date]];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM