我正在使用以下代码从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
但是输出是:
日期=(空)
年= 2001
请帮助我,为什么我会得到这种奇怪的行为?
注意:我正在使用Xcode 4.6.2和iOS 6.1
最佳答案
请尝试此确切的代码。还请注意Fixed Formats
中Date 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);
关于ios - NSDateFormatter不适用于单个硬编码日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20075718/