Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter returns wrong year [duplicate]

I need to reformat date strings I receive to another format for further use.

I get: "1.Januar 2016" which should be transformed to: 2016-01-01

My approach was to convert the original string to NSDate, then use NSDateFormatter to build the final string.

Original string:

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

Convert to 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);

Setup NSDateFormatters for month and year (day is irrelevant, is always "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);

Sadly I get this result:

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

The year is 1 behind. This only happens in January, no other month.

I guess it's a problem with the time zone, but then I don't get why only the year is behind, not the month.

like image 842
Rainer H Avatar asked Sep 17 '26 16:09

Rainer H


1 Answers

You should use yyyy, not YYYY.

like image 176
Rob Avatar answered Sep 20 '26 05:09

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!