I have been sitting with this for quite sometime now. I'm tot able to figure out, what I am doing wrong.
NSString * dateString = @"2011-11-21 13:00";
NSDateFormatter *serverDateFormatter = [[NSDateFormatter alloc] init];
[serverDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *serverDate = [serverDateFormatter dateFromString:dateString];
NSLog(@"%@", serverDate);
Output :
2011-11-21 12:00:00 +0000
Why does 13:00 get converted to 12:00? What am I doing wrong?
You need to set the time zone, example
NSString * dateString = @"2011-11-21 23:20";
NSDateFormatter *serverDateFormatter = [[NSDateFormatter alloc] init];
[serverDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
[serverDateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *serverDate = [serverDateFormatter dateFromString:dateString];
NSLog(@"%@", serverDate);
OUTPUT:
2011-11-23 14:22:10.924 xxx [23235:207] 2011-11-21 23:20:00 +0000
I think you might find the answer in this discussion. Apparently NSDateFormatter likes to use the user's settings, which may not be appropriate.
http://developer.apple.com/library/ios/#qa/qa1480/_index.html
Though I think this answer is for stopping 24-hour behavior, which is what you want to force.
I'd say you want to get the setLocale part right.
ETA: Here's some more info on this:
https://stackoverflow.com/q/7538489/290072
This will allow your code to detect whether the device will try to do 12hr or 24hr times.
What if you output via [serverDateFormatter stringFromDate:serverDate]; ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.