nsdateformatter无法与日本日历一起使用

i_r*_*aqz 5 iphone nsdate nsdateformatter ipad ios

当在模拟器和真实设备上将“设置/常规/国际/日历”设置为“日语”或“佛教”时,我在iOS上看到NSDateFormatter的问题。年份解析不正确

DateFormatter

static NSDateFormatter *formatter = nil;  // cache this the first time through


if (formatter == nil) {
    formatter = [NSDateFormatter new];
    formatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]; // Fix for QC79748 - Michael Marceau
    formatter.dateFormat = @"EEE, d MMM yyyy HH:mm:ss zzz";
    formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
    formatter.calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    formatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]] autorelease];


}

NSLog(@"CorrectDate%@",[serviceHeaders safeObjectForKey:@"Date"] );
    NSLog(@"Formatted date:%@",[formatter dateFromString:[serviceHeaders safeObjectForKey:@"Date"]]);

Output

Correct - Mon, 27 Aug 2012 16:33:14 GMT
Formatted date:0024-08-27 16:33:14 +0000
Run Code Online (Sandbox Code Playgroud)

Dav*_*d H 4

这正如它应该的那样工作。我获取了您的代码并将其添加到我的项目中,然后将模拟器设置为使用佛教日历。

NSLog(@"date=%@", [NSDate date]);
2012-08-27 18:42:10.201 Searcher[43537:f803] date=2555-08-27 22:42:10 +0000

    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; // Fix for QC79748 - Michael Marceau
    formatter.dateFormat = @"EEE, d MMM yyyy HH:mm:ss zzz";
    formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
    formatter.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    //formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]];
Run Code Online (Sandbox Code Playgroud)

然后输出:

NSLog(@"CorrectDate%@", @"Mon, 27 Aug 2012 16:33:14 GMT" );
2012-08-27 18:42:10.203 Searcher[43537:f803] CorrectDateMon, 27 Aug 2012 16:33:14 GMT

NSLog(@"Formatted date:%@",[formatter dateFromString:@"Mon, 27 Aug 2012 16:33:14 GMT"]);
2012-08-27 18:42:10.206 Searcher[43537:f803] Formatted date:2555-08-27 16:33:14 +0000
Run Code Online (Sandbox Code Playgroud)

分析:

一切都运转良好。现在是佛历2555年。当您提供公历日期并要求格式化程序使用公历时,它会正确读取它,然后将其转换为佛教日期,当您打印出来时,日期又是 2555。正如您所期望的那样。

编辑:只是为了强调一点,NSDate 总是相同的,改变的是它的表示形式。因此,我再次将日历设置为佛教日历,并使用格式化程序获取公历时间的当前时间:

NSLog(@"date=%@", [NSDate date]);
NSLog(@"Date using the Gregorian calendar: %@", [formatter stringFromDate:[NSDate date]]);
Run Code Online (Sandbox Code Playgroud)

输出

2012-08-28 07:13:10.658 Searcher[69194:f803] date=2555-08-28 11:13:10 +0000
2012-08-28 07:13:10.660 Searcher[69194:f803] Date using the Gregorian calendar: Tue, 28 Aug 2012 07:13:10 EDT
Run Code Online (Sandbox Code Playgroud)

PS:您的代码设置了两次区域设置。