-4

I got string of date regarding this format:

2011-12-29T09:09:06-0500

How can I convert this into a date object?

Blachshma
  • 17,097
  • 4
  • 58
  • 72
Hirak M.
  • 13
  • 1
  • 1
  • 4
    did you search on SO or google? – Yama Dec 30 '11 at 06:09
  • 1
    http://stackoverflow.com/questions/4999396/how-to-parse-a-date-string-into-an-nsdate-object-in-ios , http://stackoverflow.com/questions/6194998/whats-the-right-way-to-parse-an-iso8601-date-in-cocoa , http://stackoverflow.com/questions/7925038/why-nsdateformatter-can-not-parse-date-from-iso-8601-format , http://stackoverflow.com/questions/5559912/date-time-parsing-in-ios –  Dec 30 '11 at 06:30

2 Answers2

3

Try this solution

NSString *dateString = @"2011-12-29T09:09:06-0500";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

NSDate *dateFromString = [dateFormatter dateFromString:dateString];    
[dateFormatter release];
NSLog(@" dateFromString %@",dateFromString);
Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
  • 1
    Does this pick up the TZ or whack it off at Zulu or...? (I don't using anything iX.) –  Dec 30 '11 at 06:36
  • This fails on lots of ISO8601 date strings, e.g. "2013-11-27T11:28:10.201-08:00". http://en.wikipedia.org/wiki/ISO_8601 Is there anything more comprehensive? – Adrian Dec 18 '13 at 18:22
  • swift version: ` let date = "2008-12-29T00:27:42-0800" let formatter = NSDateFormatter() formatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd'T'HH:mm:ssZZZ") let final = formatter.dateFromString(date) ` – fatihyildizhan Jun 11 '15 at 14:30
1
NSString *date = [[NSDate date] description];

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

NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];
Community
  • 1
  • 1
divakar
  • 57
  • 8