gpt4 book ai didi

ios - 创建具有特定时区的 NSDate 对象

转载 作者:行者123 更新时间:2023-11-28 19:05:38 24 4
gpt4 key购买 nike

我编写了一个接受 NSDate 对象的方法,应该将其转换为具有 EST 时区的 NSDate 对象。我看到其他人完成此操作的方法是使用日期格式化程序将日期更改为具有指定时区的字符串。问题是当我尝试使用“dateFromString”将该字符串改回 NSDate 对象时。

- (NSDate*)turnToEST:(NSDate*)date
{
NSLog(@"turnToEST called with date %@", date);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"EST"]];

NSString *stringFromDate = [dateFormatter stringFromDate:date];

NSLog(@"date formatted is %@", stringFromDate);

NSDate *dateFromString = [[NSDate alloc] init];

NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
[dateFormatter2 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

dateFromString = [dateFormatter2 dateFromString:stringFromDate];

NSLog(@"date has been changed to %@", dateFromString);

return date;
}

有输出...

turnToEST called with date 2013-12-19 14:15:17 +0000
date formatted is 2013-12-19 09:15:17
date has been changed to 2013-12-19 14:15:17 +0000

我不确定为什么这与

Converting NSString to NSDate (and back again)

最佳答案

NSDate没有有关联的时区,它们代表一个抽象的时刻。因此,“具有 EST 时区的 NSDate 对象”并不存在。时区只有在为输出设置格式或尝试进行基于日历的数学运算时才会发挥作用。

NSLog 在打印其输出时始终使用 UTC。

因此,您需要时间,将其格式化为特定时区的字符串,然后将其解析回同一时间。这是按预期工作的。

关于ios - 创建具有特定时区的 NSDate 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20684233/

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