Tuesday, 14 February 2012

NSDate from Rails datetime via JSON

I'm building an iPhone app that uses a Ruby Rails JSON api and frequently I need to convert the Rails datetime string into an NSDate object. Here's how its done:

NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

NSDate *myDate = [formatter dateFromString:@"2012-02-14T12:01:41Z"]; 

and then if you need to display this later, you can convert it back to a string like this, where I display it in a British dd/mm/yyyy format:

[formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
myLabel.text = [formatter stringFromDate:myDate];

2 comments:

  1. Man! Thanks. Been looking for an hour on SO and nothing helped!

    ReplyDelete
  2. it is not workign with date format 2015-08-05T21:29:07.633Z which is also from ruby.

    ReplyDelete

Comments are moderated, so you'll have to wait a little bit before they appear!