Search code examples
nsdatensdateformatter

NSDate rolling year over to next year on Dec 31


If I have this date:

dtToUse __NSTaggedDate *    2017-12-31 05:00:00 UTC

which I get from a string using this method:

- (NSDate*) convertStringToDate : (NSString*) strToConvert andTheFormatToUse: (NSString*) strFormat {

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:strFormat];

    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];

    return [dateFormatter dateFromString:strToConvert];
}

and I use this code to display it:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/YYYY"];
    NSString* strDate = [dateFormatter stringFromDate:dtExpiration];

    self.txtCurrentField.text = [dateFormatter stringFromDate:dtExpiration];

But no matter what I do, the year increments 1 - so 2017 becomes 2018

This only happens for Dec. 31, any year. I suspect it is a time zone issue but I am not sure how to fix, as I am converting time zone to local already


Solution

  • Just try

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

    instead of

    [dateFormatter setDateFormat:@"MM/dd/YYYY"];

    After that, it will show 12/31/2017.

    Different between YYYY and yyyy. https://stackoverflow.com/a/15133656/1342266