Objective-C 中日期格式之间的转换 [英] Convert between date formats in Objective-C
问题描述
我正在尝试将日期转换为不同的格式.我将我的日期作为 NSString 接收,格式如下:EEE MMM dd HH:mm:ss ZZZ yyyy
,并试图将其更改为这种格式:dd-mm-yy代码>.但是,我无法以所需的格式获取它.
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.
这是我当前的代码:
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];
推荐答案
区域设置 en_US
不理解 IST
时区缩写.但是 en_IN
确实:
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];
正如 John Skeet 指出的,问题可能源于 IST
不独特.IST 代表 以色列标准时间 和 印度标准时间.因此,当您指定印度语言环境时,它做出了合理的假设,但对于美国语言环境,它是可以理解的混淆.
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.
无关,但请确保在输出格式化程序中使用 MM
而不是 mm
:
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];
这篇关于Objective-C 中日期格式之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!