ios_Dev
ios_Dev

Reputation: 95

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

Upvotes: 0

Views: 72

Answers (2)

Pushkraj Lanjekar
Pushkraj Lanjekar

Reputation: 2294

Problem is with time zone and you can set timezone like this:

NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

You can add any timezone instead of GMT as per your requirement. Setting NSLocale is not really mandatary if you set proper timezone as per your settings.

Upvotes: 0

Fahim Parkar
Fahim Parkar

Reputation: 31647

You need to use locale

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

Upvotes: 2

Related Questions