且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NSDate和NSDateFormatter问题

更新时间:2023-11-07 22:54:34

问题是输入日期是以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
    }
}