Search code examples
iosobjective-cnsdateformatter

NSDateFormatter showing incorrect month


Description:

I'm using NSDateFormatter for formatting date but the output is wrong the month is getting changed and even the time is changing in some cases.

Code:

NSDate *date=[NSDate date];
NSString *datestring=@"2018-07-05 12:14:29";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
[formatter setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
date = [formatter dateFromString:datestring];
NSLog(@"%@", [formatter stringFromDate:date]);

Expected Output:

2018-07-05 12:14:29

Output Got:

2018-01-05 12:14:29

Solution

  • DD is day of year

    dd is day of month

    So replace below line

    [formatter setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
    

    by this

    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];