Getting NSDate from NSString

Very useful, yet short and simple, code snippet on how to rip the NSDate from NSString using NSDateFormatter:

NSString *dateString = @"2010-01-19";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
// ta-daaa!
dateFromString = [dateFormatter dateFromString:dateString];

If you need more info about different date formats see Unicode Date Format Patterns. Of course if you usually work with standard dates you can use setDateStyle instead of setDateFormat.

Tags: , , ,

4 responses

  1. abc
    Posted February 10, 2010 at 10:09 | Permalink

    not working ..!!
    i tried this sample, m getting nil instead..

    • Foobar Pig
      Posted February 11, 2010 at 14:28 | Permalink

      Yes working. As it is mentioned in comments your dateFormatter MUST match your dateString and if it doesn’t – you get nil instead of a nice NSDate. Set dateFormatter to something that matches your date (see link to Unicode Date Format Patterns) and try again.

  2. kosssi
    Posted August 26, 2011 at 08:54 | Permalink

    Replace this code :

    NSDate *dateFromString = [[NSDate alloc] init];
    // ta-daaa!
    dateFromString = [dateFormatter dateFromString:dateString];

    by :

    NSDate *dateFromString = [[dateFormatter dateFromString:dateString] retain];


    [dateFromStrring release];

    I think is better.
    Bye

Leave a Reply