NSDate and NSDateFormatter issues

与世无争的帅哥 提交于 2020-01-13 03:52:12

问题


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"];

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]; 
}

The error I get is the following:

*** 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'

回答1:


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.

For example:

[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
    }
}



回答2:


If your call

NSDate *date = [dateFormatter dateFromString:cDate];

fails, date is NULL.

This is not written in the documentation.



来源:https://stackoverflow.com/questions/572132/nsdate-and-nsdateformatter-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!