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

查看:32
本文介绍了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天全站免登陆