Search code examples
iosobjective-cnsstringnsdatensdateformatter

How NSDateFormatter works?


I have created a below method in which i can send dateString, InputFormat & OutputFormat aswell as below.

- (NSString *)InstanceAwesomeFormatterunformattedDate:(NSString*)unformattedDate inputFormat:(NSString*)inputFormat outPutFormat:(NSString*)outPutFormat{

    //unformattedDate is 13 july 1989
    //inputFormat is @"dd MMMM yyyy" 
    //outPutFormat is @"dd"

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

    [myDateFormattr setDateFormat:inputFormat];

    NSDate *date = [myDateFormattr dateFromString:unformattedDate];
    //Why date is 1990-07-12 18:30:00 +0000
    [myDateFormattr setDateFormat:outPutFormat];

    NSString *FinalExpiryDateForUserProfile = [myDateFormattr stringFromDate:date];
    // FinalExpiryDateForUserProfile is 13 which is correct
    return FinalExpiryDateForUserProfile;

}

I am trying to understand why date prints 12 instead of 13. Any ideas


Solution

  • You need to use locale

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd"];
    NSLocale *enLocale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    [dateFormatter setLocale:enLocale];