简体   繁体   English

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

In my UIDatePicker delegate, I have repeated code that looks like the following (and works great): 在我的UIDatePicker委托中,我重复了如下代码(效果很好):

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

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". 问题在于输入日期的格式为“ yyyy-MM-dd”,但是与dateFromString一起使用的日期格式器的格式为“ 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
    }
}

If your call 如果你的电话

NSDate *date = [dateFormatter dateFromString:cDate];

fails, date is NULL. 失败,日期为NULL。

This is not written in the documentation. 这没有写在文档中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM