Reputation: 1395
First the code:
NSString* dateTimeString = [NSString stringWithFormat:@"%@%@", [aDictionary objectForKey:@"date"], [aDictionary objectForKey:@"time"]];
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyyMMddHHmm"];
NSDate* dsate = [dateFormatter dateFromString:dateTimeString];
dateTimeString string value is "201106242204"
however the dsdate gets incorrect value, in the debugger it shows: 2011-06-24 19:04:00 +0000
as you can see the hour should be 22 not 19. I have already wasted quite q bit of time on this. Tried setting the time zone, locale etc etc but nothing has any effect.
Upvotes: 1
Views: 1212
Reputation: 1395
So finally I solved this. How:
NSString* dateTimeString = [NSString stringWithFormat:@"%@%@", [aDictionary objectForKey:@"date"], [aDictionary objectForKey:@"time"]];
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
NSTimeZone* normalTimeZone = [NSTimeZone timeZoneWithName:@"EET"];
[dateFormatter setDateFormat:@"yyyyMMddHHmm"];
NSDate* date = [dateFormatter dateFromString:dateTimeString];
NSDate* correctedDate = [date dateByAddingTimeInterval:[normalTimeZone secondsFromGMT]];
I think Cocoa or iOS should have at least an API which doest try to act smart.
Upvotes: 1
Reputation: 7758
Be aware that NSDateFormatter is locale-aware. This means that even if you specify a date format string, if the current locale on a device has a different format for the string you give it, it will override the string you provided the formatter. What is your UTC offset at your present location? Because NSDateFormatter always gives UTC time, if your offset is -6, it is giving you back the correct value, just in a different timezone. One of the features of NSDateFormatter I really don't like. You might get the result you want by calling setTimeZone: on the date formatter.
Try calling -descriptionWithCalendarFormat:timeZone:locale: on the parsed NSDate instance, passing your locale and timezone. I'm curious if it outputs your desired result.
Upvotes: 2