NSDateFormatter在特定日期返回null [英] NSDateFormatter returns null for specific dates
问题描述
NSDateFormatter
遇到问题。在某些特定日期返回 null
。
I'm having a problem with the NSDateFormatter
. It is returning null
for some specific dates.
我执行此功能来调试该情况:
I did this function to debug the case:
- (void) debugTest:(NSString *)dateStr{
NSLog(@"String: %@", dateStr);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *dateObj = [df dateFromString: dateStr];
NSLog(@"Date: %@", dateObj);
}
这是某些日期的日志输出:
This is my log output for some dates:
String: 2012-10-18
Date: 2012-10-18 03:00:00 +0000
String: 2012-10-19
Date: 2012-10-19 03:00:00 +0000
String: 2012-10-20
Date: 2012-10-20 03:00:00 +0000
String: 2012-10-21
Date: (null)
String: 2012-10-22
Date: 2012-10-22 02:00:00 +0000
String: 2012-10-23
Date: 2012-10-23 02:00:00 +0000
为什么仅在 2012-10-21
日期返回null?
Why it is returning null only for the date 2012-10-21
?
我以 2011-10-01至2014-11-01
的间隔进行了其他测试,以下日期返回 null
:
I did other tests with the interval from 2011-10-01 to 2014-11-01
and the following dates returned null
:
2011-10-16, 2012-10-21, 2013-10-20, 2014-10-19
这是某种错误吗?我做错了吗?
Is this some kind of bug? I am doing something wrong?
推荐答案
我将回答我自己的问题,只是为了注册,以防有人遇到相同的问题:
I will answer my own question just to register in case of someone get the same problem:
我已添加到日期格式化程序
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@ en_US_POSIX]]]; code>和
[df setTimeZone:[NSTimeZone timeZoneWithName:@ GMT]];
。
I added to my date formatter
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
AND [df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
.
所以,我的新代码是:
- (void) debugTest:(NSString *)dateStr{
NSLog(@"String: %@", dateStr);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *dateObj = [df dateFromString: dateStr];
NSLog(@"Date: %@", dateObj);
}
我认为问题与设备的配置有关,设置这两个属性解决了这个问题。
I think the problem was related to the device's configuration, setting the two properties fixed the problem.
这篇关于NSDateFormatter在特定日期返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!