I am trying to convert nsstring to nsdate and then to the systemtimezone. Is my code right? Any help appreciated.
NSString *str=@"2012-01-15 06:27:42";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateFromString = [dateFormatter dateFromString:str];
NSDate* sourceDate = dateFromString;
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT-07:00"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
bottomLabel2.text=[NSString stringWithFormat:@"- %@ -",destinationDate];
The code result is 2012-01-15 06:27:42 +0000 which is the same as the source!
I think I can see what the problem is here - it's this line:
GMT-07:00
is not a valid abbreviation for this method. If you call[NSTimeZone abbreviationDictionary]
you'll get a dictionary containing all available abbreviations. You need to use the actual abbreviation (eg, 'PST' for Pacific Standard Time), and not the format "GMT-07:00".To save you time, here's the full list of supported abbreviations using
NSTimeZone
.