objective-c - 如何禁止 NSDate 进行自动时区转换

标签 objective-c ios macos nsdateformatter

我的 Web 服务在 JSON 响应中返回以下日期字符串。此日期字符串已采用 UTC。

{"last_updated_at": "2012-11-19 07:55:30"}

我使用 NSDateFormatter 解析响应日期字符串,如下所示。

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

if ([ticketFields objectForKey:@"last_updated_at"] != [NSNull null]) {
    self.lastUpdatedAt = [dateFormatter dateFromString:[ticketFields objectForKey:@"last_updated_at"]];

    NSLog(@"Time Response string %@", [ticketFields objectForKey:@"last_updated_at"]);
    NSLog(@"Formatted NSDate %@", self.lastUpdatedAt);
}

这是我的日志输出

Time Response string 2012-11-21 11:38:44
Formatted NSDate 2012-11-21 06:08:44 +0000

如您所见,NSDateFormatter 除了解析日期字符串外,还认为日期字符串是 UTC+530(我的本地时区),并通过从给定日期减去 530 小时自动将其转换为 UTC。我不希望这发生。 NSDateFormatter 应该从给定的字符串中转换日期,理想情况下会给出以下输出。

Time Response string 2012-11-21 11:38:44
Formatted NSDate 2012-11-21 11:38:44 +0000

最佳答案

此数据格式化程序配置阻止了转换并将日期响应字符串视为 UTC 日期。

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

它奏效了。

关于objective-c - 如何禁止 NSDate 进行自动时区转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13507016/

相关文章:

objective-c - 在选项卡栏和导航栏内弹出 View 时遇到问题

objective-c - MVC 和使用 UIButton 动态创建 UI 元素

objective-c - 是否可以在 cocoa xib/nib 中嵌入终端窗口?

objective-c - UIGestureRecognizer - 获取对触摸的 UIViewController 的引用而不是它的 View ?

swift - CALayer.compositingFilter 适用于 ObjectiveC 但不适用于 swift

ios - UILabels 将动态信息放入标签中并分别列出每个标签?

ios - *.aif 和 *.caf 文件之间有区别吗?

c# - 需要知道如何在 Xamarin.iOS 中终止后台进程

objective-c - NSApplicationPresentationHideDock 没有效果

macos - 记住 OS X 中的终端状态(比如 shell 的 Fluid...)