【发布时间】:2013-12-03 06:02:50
【问题描述】:
我正在使用以下代码从 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
【问题讨论】:
-
我试过你的代码它也适用于硬编码日期。我的日志为:日期 = 2009 年 4 月 15 日,年份 =2009
-
我试过了,它对我有用。问题,为什么是 dateC 的 alloc/init/autorelase?
-
我总是得到这个:-[__NSCFCalendar components:fromDate:]: date cannot be nil 我的意思是真的,你认为这个操作对于一个 nil 日期应该意味着什么?暂时避免了一个例外。此投诉将报告其中一些错误,然后进一步的违规行为将简单地默默地执行 nil 导致的任何随机事情。
-
它在 Xcode 5.0.1 iOS7 上运行良好: NSDate *dateC= [[NSDate alloc] init]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setLocale:[NSLocale currentLocale]]; [dateFormat setDateFormat:@"MM/dd/yyyy HH:mm"]; dateC = [dateFormat dateFromString:@"04/15/2009 00:00"]; // 只有这个日期给出空日期。 NSLog(@"date = %@",dateC);
-
几乎可以肯定它是您的语言环境 - 尝试使用像这样的语言环境 "[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]" 和/或日历 [dateFormat setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier :NSGregorianCalendar]]
标签: ios iphone nsdate nsdateformatter nsdatecomponents