You can use NSDateFormatter to achieve this.
NSString *dateString = @"2013-05-28 10:56:31";
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//Special Locale for fixed dateStrings
NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocale:locale];
//Assuming the dateString is in GMT+00:00
//formatter by default would be set to local timezone
NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
[formatter setTimeZone:timeZone];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date =[formatter dateFromString:dateString];
//After forming the date set local time zone to formatter
NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
[formatter setTimeZone:localTimeZone];
NSString *newTimeZoneDateString = [formatter stringFromDate:date];
NSLog(@"%@",newTimeZoneDateString);
A few pointers for using dateFormatter.
- If the string don't contain any information about timezone and it is not in same timezone as in the device always set the timezone to the dateFormatter.
- For fixed format dateStrings always use
en_US_POSIX
locale
- NSDate when logged in console always show in GMT+00:00. NSDate don't have timezone, it just differs when represented in different timezone.
- Convert the formed date to any timezone, by setting new timezone to formatter. Formatter never changes the date it just recalculates how it will be represented in this new timezone.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…