Reputation: 71
I'm trying to create a date object with the specified formatter but date formatter_datefromstring method returns nil. Please let me know with the clear documentation samples. The String am trying to parse is "2:00 AM PDT on September 24, 2017". Thanks in advance
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setLocale:[NSLocale currentLocale]];
[dateFormat setDateFormat:@"h:mm a Z 'on' MMMM d, yyyy"];
NSLog(@"dateStr:==============> %@", dateStr);
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(@"Date:------------->%@", date);
return date;
Upvotes: 0
Views: 64
Reputation: 479
Use the below locale the avoid returning nil value.
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
Vote my code if it is usefull
Upvotes: 0
Reputation: 124
Can you check your dateStr date format and your given format same or not. If both are not same format you will get nil object. Try dateStr format in given below example.
NSString *dateStr = @"10:23 am Z on September 30, 2017";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormat setLocale:[NSLocale currentLocale]];
[dateFormat setDateFormat:@"h:mm a Z 'on' MMMM d, yyyy"];
NSLog(@"dateStr:==============> %@", dateStr);
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(@"Date:------------->%@", date);
In console you will get 2017-09-23 09:54:04.654597+0530 Date[4068:79926] dateStr:==============> 10:23 am Z on September 30, 2017 2017-09-23 09:54:04.657359+0530 Date[4068:79926] Date:------------->Sat Sep 30 15:53:00 2017
Upvotes: 0
Reputation: 318804
You are using the wrong timezone specifier. Z
is for timezones such as -0800
. You need z
for short timezone abbreviations like PDT
.
Also, there is no reason to set the formatter's local to currentLocale
and the timezone to systemTimeZone
since those are the defaults. And the timezone of the formatter is irrelevant when the string you are parsing contains timezone information.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"h:mm a z 'on' MMMM d, yyyy"];
NSLog(@"dateStr:==============> %@", dateStr);
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(@"Date:------------->%@", date);
return date;
However, since you are parsing a fixed format date string that is in English, you really should set the formatter's locale to the special locale of en_US_POSIX
. This will ensure it handles the English month name no matter the user's locale.
[dateFormat setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
Upvotes: 1