NSDateFormatter不适用于单个硬编码日期

时间:2013-11-19 15:37:38

标签: ios iphone nsdate nsdateformatter nsdatecomponents

我使用以下代码从NSString中检索日期和年份。我在NSLog语句中打印它们。

NSDate *dateC= [[[NSDate alloc] init] autorelease];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[NSLocale currentLocale]];
[dateFormat setDateFormat:@"MM/dd/yyyy HH:mm"];
dateC = [dateFormat dateFromString:@"04/15/2009 00:00"];  // Only this date gives null date.
[dateFormat setDateFormat:@"MMM dd, yyyy"];
NSLog(@"date = %@",[dateFormat stringFromDate:dateC]);

NSCalendar* calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:dateC];
NSLog(@"year =%d",[components year]);
[dateFormat release];

此代码适用于除代码中提及的日期之外的每个日期 输出应为:

日期= 2009年4月15日
年= 2009年

但输出是:

date =(null)
年= 2001年

请帮助我为什么我会得到这种奇怪的行为?
注意:我使用的是Xcode 4.6.2和iOS 6.1

2 个答案:

答案 0 :(得分:3)

请尝试这个确切的代码。另请注意Fixed FormatsDate Formatters Guide下的部分,链接到NSDateFormatter类说明中。

// NSDateFormatter Class Description says:
// Note that although setting a format string (setDateFormat:) in principle specifies an
// exact format, in practice it may nevertheless also be overridden by a user’s
// preferences—see Data Formatting Guide for more details.
NSLocale *locale;

NSLocale *curLocale = [NSLocale currentLocale];
NSLocale *usaLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
if([curLocale.localeIdentifier isEqualToString:usaLocale.localeIdentifier]) {
    locale = [[NSLocale alloc] initWithLocaleIdentifier:usaLocale.localeIdentifier];
    NSLog(@"Created a new one");
} else {
    NSLog(@"USed the old one");
    locale = usaLocale;
}
assert(locale);

NSDate *dateC= [[NSDate alloc] init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:locale];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
assert(calendar);
[dateFormat setCalendar:calendar];
[dateFormat setDateFormat:@"MM/dd/yyyy HH:mm"];

dateC = [dateFormat dateFromString:@"04/15/2009 00:00"];  // O
NSLog(@"DATE: %@", dateC);

答案 1 :(得分:0)

如果显示不同的小时,您可能需要设置默认时区(这只发生在ios7之后)

[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];