How to create an NSDate object from a string such as 22/04/2013

Here’s how we can do this, with the help of our old friend the NSDateFormatter:

    // here we have a date
    NSString *dateString = @"11/01/1989";
    // convert it into an NSDate object
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    NSDate *theDate = [formatter dateFromString:dateString];
    // so what is that?
    NSLog(@"Your Date Object is %@", theDate);

    // Your Date Object is 1989-01-11 05:00:00 +0000

Note the lower case yyyy. In many cases, YYYY and yyyy will yield the same result, but there is a difference:

    [formatter setDateFormat:@"dd/MM/yyyy"];

    // Your Date Object is 1988-12-25 05:00:00 +0000

As Apple put it:

It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.