Search code examples
iosnsdatensdateformatter

NSDateFormatter error, return date one year ago


Code:

NSString *ds = @"2013-02-25";
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd"];
NSDate* date = [formatter dateFromString:ds];
NSLog(@"%@", date); //2012-02-24 16:00:00 +0000
[formatter setDateFormat:@"MMM dd, YYYY"];
NSLog(@"%@", [formatter stringFromDate:date]); //Feb 25, 2012

Is there something wrong I made? Or iOS 6 SDK bug?


Solution

  • Change this :

    [formatter setDateFormat:@"YYYY-MM-dd"];
    [formatter setDateFormat:@"MMM dd, YYYY"];
    

    To :

    [formatter setDateFormat:@"yyyy-MM-dd"];
    [formatter setDateFormat:@"MMM dd, yyyy"];
    

    Reason for the error,

    It's a common mistake 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.