iOS   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了iphone – nsdateformatter不使用日历大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
当设置/通用/国际/日历在模拟器和真实设备上设置为日语或佛教时,我在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

解决方法

这是正常的.我拿了你的代码并将它添加到我的项目中,然后将模拟器设置为使用佛教日历.

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

然后输出

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

分析:

一切都很完美.在佛教历法中,现在是2555年.当您提供格里高利日期,并要求格式化程序使用格里高利历时,它会正确读取,然后将其转换为佛教日期,当您打印出日期时,日期再次为2555.正是你所期待的.

编辑:只是按下这一点,NSDate始终是相同的,它的表示有什么变化.所以我再次将日历设置为Buddhist,并使用格式化程序获取格里高利时间的当前时间:

NSLog(@"date=%@",[NSDate date]);
NSLog(@"Date using the Gregorian calendar: %@",[formatter StringFromDate:[NSDate date]]);

输出

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

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

大佬总结

以上是大佬教程为你收集整理的iphone – nsdateformatter不使用日历全部内容,希望文章能够帮你解决iphone – nsdateformatter不使用日历所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。