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

标签 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

但是输出是:
日期=(空)
年= 2001

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

最佳答案

请尝试此确切的代码。还请注意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);

关于ios - NSDateFormatter不适用于单个硬编码日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20075718/

相关文章:

ios - 选择文本字段时使 UITableView 滚动

objective-c - iOS 上自动续订订阅所需的服务器

iphone - ALAssetsLibrary 无法检索物理 iOS 4.1 iPod 设备中的图像 URL?

iphone - 当特定的 nsdate 已过时触发方法

objective-c - 将时间戳转换为 nsdate 格式

ios - 使用信标测距更新 WatchKit 应用程序

ios - 如何使用 swift 添加 uitableview 的按钮结束

ios - 当应用程序直接在设备中运行并创建 ipa 文件时,为什么设备 token 生成不同?

iphone - 从 UIWebview 获取响应

ios - 如何将像 "05/20/2015 05:27 pm"这样的日期字符串转换为 NSDate 然后转换为时间戳