Reputation: 1721
I need to convert
3/27/2015 5:45:00 AM
string into an NSDate object.
I tried this;
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
but it does not work.
What might be wrong that i could not figure out?
Thanks
Code added;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *tempDate = [dateFormatter dateFromString:@"3/27/2015 5:45:00 AM"]
EDIT:
It is somehow, because of time slice(AM/PM) gets null. I removed "a" from dateformatter and AM from the string. it is OK. But still do not know what is wrong with "a" ?
Upvotes: 2
Views: 438
Reputation: 69459
You forgot the add the locale for the date locale to the date formatter.
The code will run fine an any device set to US english, but other locales will fail. Just add the en_US_POSIX
as the locale for the date formatter:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
NSDate *tempDate = [dateFormatter dateFromString:@"3/27/2015 5:45:00 AM"];
Upvotes: 3
Reputation: 14000
I don't understand your question.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *tempDate = [dateFormatter dateFromString:@"3/27/2015 5:45:00 AM"];
NSLog(@"%@", tempDate); // prints "2015-03-27 09:45:00 +0000" to the console.
This is the code that you have posted. I copied it verbatim. The NSLog
that I included correctly prints a date and not nil
.
Upvotes: 0