Nil NSDate试图在祖鲁时间从UTC字符串获取日期 [英] Nil NSDate when trying to get date from UTC string in zulu time

查看:130
本文介绍了Nil NSDate试图在祖鲁时间从UTC字符串获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中编写一个iPhone应用程序,我有一个字符串形式的日期(UTC格式,最后用Z表示零UTC偏移,或祖鲁时间),我需要解析为 NSDate object。


一些代码:

Writing an iPhone app in Objective-C, I have a date in string form (in UTC format, with a Z on the end to denote zero UTC offset, or zulu time), which I need to parse into an NSDate object.

A bit of code:

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSString* str = @"2009-08-11T06:00:00.000Z";
NSDate* date = [df dateFromString:str];


通过调试器运行, date 结束 nil !我假设它与我的日期格式字符串有关。

如何修复它以正确解析日期字符串?


想到的是日期格式文字中的 Z ,将日期格式设置为 yyyy-MM-dd'T'HH:mm:ss.SSS'Z '


这样可行,除非将Z解析为文字,日期会丢失偏移信息,因此不明确,因此被解释为本地时间。


例如,如果要解析的字符串是2009-08-11T06:00:00.000Z(6:00祖鲁时间),则会被解释为当地时间的6:00,并且然后将应用不正确的偏移。然后将其解析为2009-08-11T06:00:00.000-600(12:00祖鲁时间),偏移量取决于用户的偏移量。


谢谢!

Running this through the debugger, date ends up nil! I'm assuming it has something to do with my date format string.

How can I fix it to correctly parse the date string?

A thought would be to make the Z in the date format literal, a la setting the date format to yyyy-MM-dd'T'HH:mm:ss.SSS'Z'.

That would work, except when the Z is parsed as a literal, the date loses offset information, and so is ambiguous, and therefore interpreted to be local time.

For example, if the string to parse was 2009-08-11T06:00:00.000Z (6:00 zulu time) it would be interpreted as 6:00 local time, and an incorrect offset would then be applied. It would then be parsed as 2009-08-11T06:00:00.000-600 (12:00 zulu time) with the offset depending on the user's offset.

Thanks!

推荐答案

我也有这个问题,我不确定这是Apple代码中的API错误,还是我缺乏理解,但我通过在我的日期字符串中使用小时偏移来解决这个问题。

I've had this problem also, I'm not sure if it's a API bug within Apple's code, or my lack of understanding, but I've worked around it by using hour offsets in my date strings.

如果您将示例中的代码更改为:

If you change the code in your example to:

NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSString* str = @"2009-08-11T06:00:00.000-0700";   // NOTE -0700 is the only change
NSDate* date = [df dateFromString:str];

它现在将解析日期字符串。当然-0700小时是我的抵消,你必须把它改成你的。希望这会有所帮助。

It will now parse the date string. Of course the -0700 hours is my offset, you'd have to change it to yours. Hope this helps.

这篇关于Nil NSDate试图在祖鲁时间从UTC字符串获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆