-->

Producing an NSDate with NSDateFormatter Yielding

2020-07-23 06:43发布

问题:

I am trying to produce a date from a string with the following:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, yyyy HH:mm:ss"];
NSLog(@"ENDINGDATE: %@", [closure objectForKey:@"ENDINGDATE"]);
NSDate *tempDate = [dateFormatter dateFromString:[closure objectForKey:@"ENDINGDATE"]];

The ENDINGDATE NSLog produces the following:

ENDINGDATE: April, 21 2011 20:00:00

Everything seems to be fine, so I am stumped as to why tempDate is being set to nil. Any ideas? Thanks!

回答1:

The , is misplaced. It should be after MMMM. So the format should have defined as MMMM, dd yyyy HH:mm:ss.

[dateFormatter setDateFormat:@"MMMM, dd yyyy HH:mm:ss"];


回答2:

Please try after removing comma...

You can use following date formates:

d Day of the month as digits; no leading zero for single-digit days.

dd Day of the month as digits; leading zero for single-digit days.

EEE Day of the week as a three-letter abbreviation.

dddd Day of the week as its full name.

m Month as digits; no leading zero for single-digit months.

mm Month as digits; leading zero for single-digit months.

MMM Month as a three-letter abbreviation.

mmmm Month as its full name.

yy Year as last two digits; leading zero for years less than 10.

yyyy Year represented by four digits.

h Hours; no leading zero for single-digit hours (12-hour clock).

hh Hours; leading zero for single-digit hours (12-hour clock).

H Hours; no leading zero for single-digit hours (24-hour clock).

HH Hours; leading zero for single-digit hours (24-hour clock).

M Minutes; no leading zero for single-digit minutes.

Uppercase M unlike CF timeFormat‘s m to avoid conflict with months.

MM Minutes; leading zero for single-digit minutes.

Uppercase MM unlike CF timeFormat‘s mm to avoid conflict with months.

s Seconds; no leading zero for single-digit seconds.

ss Seconds; leading zero for single-digit seconds.



回答3:

Yep, if the prototype format doesn't exactly match the actual format you get nil. The misplaced comma is likely your problem (or at least part of it).