gpt4 book ai didi

ios - 将日期转换为设备时区

转载 作者:行者123 更新时间:2023-11-29 04:10:42 26 4
gpt4 key购买 nike

我正在从服务器解析 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对象只是表示日期的抽象,它与显示无关。

关于ios - 将日期转换为设备时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14444907/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com