Question

Possible Duplicate:
Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset?

I am writing an iPhone app, which brings time from Ruby on Rails web service. The time string i get from JSON response has following format. "2012-12-01T01:01:00Z" I want to get system time zone based time from this. How can I do?

Was it helpful?

Solution

If you need your times to match on server and app, you can just set the time zone of your date formatter you use for converting the JSON date string to an NSDate to use GMT when you get it from the web service. So your date formatter should be initialized like this:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss'Z'"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

Then get your date string from the JSON and create a date with it:

NSDate *dateFromServer = [dateFormatter dateFromString:[json valueForKey:@"created_at"]]
// Do something with dateFromServer like save it to CoreData

Then, later on, when you want to display that date, just create another date formatter that you want to use to display the date in your local time. NSDate will default to the system timezone and it should display the correct time.

NSDateFormatter *displayDateFormatter = [[NSDateFormatter alloc] init];
[dispalyDateFormatter setDateFormat:@"MMM dd, YYYY"]; // ex. Jul 21, 2012

NSDate *dateFromCoreData = [managedObject valueForKey:@"CreatedAt"];
NSString *dateString = [displayDateFormatter stringFromDate:dateFromCoreData];
// Display your date string in a UILabel or Table View Cell, etc.

Best regards.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top