0

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

ios_Dev
  • 95
  • 1
  • 10

2 Answers2

2

You need to use locale

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
NSLocale *enLocale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:enLocale];
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
  • thanks Fahim, but earlier i tried with YYYY instead of yyyy , does that make difference ? and if this method is a class method that would not make any difference or does it ? Kindly explain thanks again – ios_Dev Dec 26 '16 at 06:38
  • @ios_Dev : You have to use YYYY – Fahim Parkar Dec 26 '16 at 06:41
0

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.

Pushkraj Lanjekar
  • 2,254
  • 1
  • 21
  • 34
  • thanks sir, so lets say for Indian time zone, what would I assign instead of @"GMT" ? – ios_Dev Dec 26 '16 at 06:49
  • If its Indian Time Zone then It should work with @"GMT". I said set different time zone it means, zones like GMT, PST or UTC. For indian timezone, GMT should work. And if you want to set time zone as per devices time zone, Refer This: https://agilewarrior.wordpress.com/2012/06/27/how-to-convert-nsdate-to-different-time-zones/ – Pushkraj Lanjekar Dec 26 '16 at 07:00