【问题标题】:NSDateFormatter returns wrong year [duplicate]NSDateFormatter 返回错误的年份[重复]
【发布时间】:2015-08-21 12:42:37
【问题描述】:

我需要将收到的日期字符串重新格式化为另一种格式以供进一步使用。

我得到:“1.Januar 2016”应该转换为:2016-01-01

我的方法是将原始字符串转换为 NSDate,然后使用 NSDateFormatter 构建最终字符串。

原字符串:

NSString *originalDate = @"1.Januar 2016";

转换为 NSDate:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"de_DE"];
dateFormatter.dateFormat=@"dd.MMMM yyyy";
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSDate *date = [dateFormatter dateFromString:originalDate];
NSLog(@"nsdate = %@", date);

为月份和年份设置 NSDateFormatters(日期无关,始终为“1”):

NSDateFormatter *dateMonthFormatter = [[NSDateFormatter alloc] init];
dateMonthFormatter.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"de_DE"];
dateMonthFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
dateMonthFormatter.dateFormat=@"MM";

NSDateFormatter *dateYearFormatter = [[NSDateFormatter alloc] init];
dateYearFormatter.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"de_DE"];
dateYearFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
dateYearFormatter.dateFormat=@"YYYY";

NSString *finalString = [NSString stringWithFormat:@"%@-%@-01",[dateYearFormatter stringFromDate:date], [dateMonthFormatter stringFromDate:date]];

NSLog(@"date = %@", finalString);

很遗憾我得到了这个结果:

2015-08-21 14:36:05.189 Test[315:63610] nsdate = 2016-01-01 00:00:00 +0000
2015-08-21 14:36:05.194 Test[315:63610] date = 2015-01-01

年份落后 1 年。这只发生在一月份,没有其他月份。

我猜这是时区的问题,但我不明白为什么只落后年份,而不是月份。

【问题讨论】:

  • 问题已解决,非常感谢。
  • 你是如何解决这个问题的?

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

你应该使用yyyy,而不是YYYY

【讨论】:

  • Date Format Table 来看,YYYY 是“年”(在基于“一年中的一周”的日历中)。通常长度指定填充,但对于两个字母,它还指定最大长度。这一年名称用于 ISO 8601 定义的 ISO 年-周日历,但可用于需要处理周日期的基于非公历的日历系统。可能并不总是与日历年的值相同。底线,使用YYYY 格式化一年中的一周,否则使用yyyy
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多