NSDateFormatter dateFromString返回nil [英] NSDateFormatter dateFromString returns nil

查看:208
本文介绍了NSDateFormatter dateFromString返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

NSString *_date = @"Tue, 23 Nov 2010 16:14:14 +0000";
NSDateFormatter *parser = [[NSDateFormatter alloc] init];
[parser setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss '+0000'"];
[parser setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSDate *date = [parser dateFromString:_date];

这不会运行:'date'设置为'nil'。我尝试使用

This doesn't run : 'date' is set to 'nil'. I tried with

[parser setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];

没有更多成功...

提前感谢

推荐答案

添加此行:

NSDateFormatter *parser = [[NSDateFormatter alloc] init];
[parser setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];

默认情况下, NSDateFormatter 使用系统的当前语言环境,这可能会根据当前用户的首选项而有所不同。上面的日期字符串( @Tue,23 Nov 2010 16:14:14 +0000)包含可能不会出现的英文单词(Tue,Sep

and it will work. By default, NSDateFormatter uses the system's current locale, which can vary depending on the current user's preferences. The date string above (@"Tue, 23 Nov 2010 16:14:14 +0000") contains English words ("Tue", "Sep") that would potentially not be recognized by the date formatter if the locale would be set to anything other than English.

此外,来自非西方文化的用户可能使用使用不同日历的区域设置在西方世界使用的公历。如果没有显式设置语言环境,日期格式化程序可能能够解析日期,但结果 NSDate 将代表一个完整的其他时间点。

Moreover, users from non-western cultures might use locales that use a different calendar than the Gregorian calendar that's used in the western world. If you did not explicitly set the locale, the date formatter might be able to parse the date but the resulting NSDate would represent a whole other point in time.

区域设置标识符 @en_US_POSIX用于此目的。即使@en_US区域设置应该改变其默认设置,它也不会改变。

The locale identifier @"en_US_POSIX" is meant for this purpose. It is guaranteed to not change even if the @"en_US" locale should someday change its default settings.

这篇关于NSDateFormatter dateFromString返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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