Reputation: 6384
I am getting this string:
November, 28 2013 09:05:59
and am trying to convert to date using this code:
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, yyyy HH:mm:ss"];
NSDate* dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:strToConvert];
return dateFromString;
but instead of getting back the above format I am getting:
2013-11-28 21:05:59 +0000
Edit: I said nil initially but have since got it to return something, just not what I was expecting.
Upvotes: 0
Views: 53
Reputation: 53112
My guess is that you're converting a string to a date and then printing like this:
NSLog(@"dateFromString: %@", dateFromString);
And you're confused why it isn't the format you specified. The format does not affect the date. An NSDate is a fixed point in time, the date formatter only provides the necessary information for how to turn your string to this fixed point. When you print it, it prints in its standard format. I assume that dateFormatter is a global variable because you aren't defining it here. If that's the case, you'd be better off printing like this:
NSLog(@"dateFromString: %@", [dateFormatter stringFromDate:dateFromString]);
After seeing your update, I noticed another problem:
NSString * strToConvert = @"November, 28 2013 09:05:59";
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
// NOTICE MOVED COMMA
[dateFormatter setDateFormat:@"MMMM, dd yyyy HH:mm:ss"];
NSDate* dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:strToConvert];
NSLog(@"dateFromString unformatted: %@", dateFromString);
NSLog(@"dateFromString formatted : %@", [dateFormatter stringFromDate:dateFromString]);
Will print:
2014-03-21 15:27:39.532 dateFromString unformatted: 2013-11-28 14:05:59 +0000
2014-03-21 15:27:39.533 dateFromString formatted: November, 28 2013 09:05:59
Upvotes: 1