iOS 7: Convert NSDate to string with custom timezone and get back new NSDate

Artem Z. picture Artem Z. · Feb 5, 2014 · Viewed 13.1k times · Source

I wish to modify current system time (set a custom NSTimeZone) and get back a new NSDate object.

The code I've made

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSLog(@"System time: %@", [dateFormatter stringFromDate:[NSDate date]]);
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Aqtobe"]];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"Aqtobe time: %@", dateString);

The output

System time: 2014-02-05 10:00:46 +0000

Aqtobe time: 2014-02-05 15:00:46 +0500

But if I try to get new NSDate object from Aqtobe time:

NSLog(@"New NSDate: %@", [dateFormatter dateFromString:dateString]);

I get

New NSDate: 2014-02-05 10:02:40 +0000

Where I was wrong? Thanks in advance

Answer

Nitesh Borad picture Nitesh Borad · Jun 6, 2014

NSDate always returns date in GMT +0:00. So, it (NSDate object) always have correct converted value but in GMT +0:00. So for using it as text you will always have to use same date formatter with same zone. If you want to use date as string from date in other places (out of dateformatter object scope), it is better to make special method for conversion.

It is explained clearly below with example:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";

NSLog(@"System time: %@", [dateFormatter stringFromDate:[NSDate date]]);

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Aqtobe"]];

NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"Aqtobe time: %@", dateString);

// date will always contain value in GMT +0:00
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"New NSDate (NSDate): %@", [dateFormatter stringFromDate:date]);

// converts date into string
NSLog(@"New NSDate (NSString): %@", [dateFormatter stringFromDate:date]);

For detailed explaination you can refer this question: Does [NSDate date] return the local date and time?