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.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.