【发布时间】: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