NSDate和NSDateFormatter问题 [英] NSDate and NSDateFormatter issues
问题描述
我有点难以理解为什么下面的代码崩溃了我的一个应用程序:
I'm having slight difficulty in understanding why the following code is crashing an app of mine:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM d, yyyy"];
NSDate *date = [dateFormatter dateFromString:cDate];
datePicker.date = date;
NSString *dateStr = [dateFormatter stringFromDate:date];
[dateLabel setText:dateStr];
[dateFormatter release];
如果我评论上面的内容,此外,如果我将日期格式更改为以下,则不会发生崩溃:
If I comment the above out, app is fine. Also if I change the date format to the following no crash happens:
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
在我的 UIDatePicker
委托中,代码看起来像下面的(和工程很好):
In my UIDatePicker
delegate, I have repeated code that looks like the following (and works great):
-(IBAction)datePickerValueChanged:(id)sender
{
NSDate *date = [datePicker date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"MMMM d, yyyy"];
NSString *dateStr = [dateFormatter stringFromDate:date];
[dateLabel setText:dateStr];
}
我得到的错误如下:
*** Assertion failure in -[UIDatePickerView _updateBitsForDate:andReload:animateIfNeeded:], /SourceCache/UIKit/UIKit-747.38/UIDatePicker.m:892
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: date'
推荐答案
问题是输入日期是以yyyy-MM-dd格式,但是你使用dateFromString的日期格式化格式化为MMMM d,yyyy。
The problem is that the input date is in the "yyyy-MM-dd" format, but the date formatter you're using with dateFromString is formatted "MMMM d, yyyy". You'll need to try parsing with both formats if you're desiring both formats to be accepted.
例如:
[dateFormatter setDateFormat:@"MMMM d, yyyy"];
NSDate *date = [dateFormatter dateFromString:cDate];
if (date == nil) {
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
date = [dateFormatter dateFromString:cDate];
if (date == nil) {
// Handle the situation where the date string could not be parsed
}
}
这篇关于NSDate和NSDateFormatter问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!