Search code examples
iosobjective-cnsdatensdateformatterfoundation

NSDateFormatter transition to NSString error


here is the code

NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"YYYY-MM-dd"];
NSString * dateNow = [formatter stringFromDate:[NSDate date]];

and the debugger shows

enter image description here

and why the number of the year is 2016?


Solution

  • Use yyyy instead of YYYY in your NSDateFormatter as

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

    why the number of the year is 2016?

    The reason being:

    The "YYYY" is a week-based calendar year.

    The "yyyy" is an ordinary calendar year.