I want to apologize ahead of time for asking a repeat question, but none of the other solutions have worked for me yet. Every time I try to pass a date string to the dateFromString function I get nil. I haven't read anywhere that things have changed since the iOS 7 update, but I am current on updates if that makes a difference on whether or not this still works the same way.
This is the code I'm using to create the date from string:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setLocale:[NSLocale systemLocale]];
[dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
[dateFormat setFormatterBehavior:NSDateFormatterBehaviorDefault];
NSDate *date = [[NSDate alloc] init];
date = [dateFormat dateFromString:dateString];
return date;
I've set up my dateFormat based on all the solutions I've read to solve this problem, but none of these settings have solved by problem. The systemLocale is definitely set up for English so that should not be causing any issues.
This is the dateString I'm passing to dateFromString:
Wednesday, October 9, 2013 at 2:40:29 PM Pacific Daylight Time
Thanks for the help!
There are two issues here:
The format of date string the formatter is expecting (
@"yyyy-MM-dd hh:mm:ss"
) is different from the format of the date string you're trying to parse (@"EEEE, MMMM d, yyyy 'at' h:mm:ss a zzzz"
).Setting the formatter's locale to
[NSLocale systemLocale]
is causing[dateFormat dateFromString:]
to returnnil
. Set it to[NSLocate currentLocale]
.The full code for the formatter should be:
Your date format doesn't match the string that you're passing, your dateString should be in this formate as per your [dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
2013-10-09 02:40:29
nil means dateFormat object was unable to parse your string.
You're trying to use dateFromString but the Format you have passed to your Formatter is different of what you're using in dateString.
Try to use this config in your dateFormat:
E',' M d',' yyyy 'at' hh:mm:ss aa z
Yet another way to get nil is if you use
hh
and your hours are on the 24 hr clock and > 12, in that case, you needHH
(orH
, for zero-padded).That is:
Hat-tip to @neilco (see comments below his answer) for this. If you like this answer, please up-vote his, too.
According to NSDateFormatter documentation :
If your date format is
2017-06-16T17:18:59.082083Z
thendateFormat
property should look like thisyyyy-MM-dd'T'HH:mm:ss.SSSSSSZ
.Swift 3