Convert between date formats in Objective-C

一笑奈何 提交于 2019-12-24 16:31:10

问题


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];

回答1:


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];


来源:https://stackoverflow.com/questions/29212471/convert-between-date-formats-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!