1

I am trying to convert a date into a different format. I'm receiving my date as an NSString with the following format: EEE MMM dd HH:mm:ss ZZZ yyyy, and am attempting to change it to this format: dd-mm-yy. However, I am not able to get it in desired format.

This is my current code:

    NSString *dateStr = [NSString stringWithFormat:@"%@",[dict valueForKey:@"createdOn"]];

    [dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss zzz yyyy"];
    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"IST"];
    dateFormatter.timeZone = gmt;
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    NSDate *dateFromString = [dateFormatter dateFromString:dateStr];

    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
    [dateFormatter2 setDateFormat:@"dd/mm/yyyy"];
    NSString *newDateString = [dateFormatter2 stringFromDate:dateFromString];
Erik S
  • 1,939
  • 1
  • 18
  • 44
DJB
  • 857
  • 7
  • 15
  • 1
    How are you getting the format? dd/mm/yyyy? Maybe try @"dd-MM-yyyy". – Peter Segerblom Mar 23 '15 at 14:17
  • @Rob: I am getting date as string in this format "Tue Mar 24 08:28:48 IST 2015" and i am attempting to change it to "dd-MM-yyyy". – DJB Mar 24 '15 at 03:04
  • I am getting dateFromString as nil. after getting nil value no matter what dateFormatter2 outputs which is nothing but nil again. – DJB Mar 24 '15 at 03:16

1 Answers1

2

The locale en_US doesn't understand the IST time zone abbreviation. But en_IN does:

NSString *dateStr = @"Tue Mar 24 08:28:48 IST 2015";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss zzz yyyy"];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_IN"];
NSDate *dateFromString = [dateFormatter dateFromString:dateStr];

As John Skeet points out, the issue probably stems from the fact that IST is not unique. IST stands for both Israel Standard Time, and India Standard Time. Thus, when you specify India locale, it makes a reasonable assumption, but for US locale, it is understandably confused.


Unrelated, but make sure to use MM rather than mm in your output formatter:

NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:@"dd/MM/yyyy"];
NSString *newDateString = [dateFormatter2 stringFromDate:dateFromString];
Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044