Question

After going almost crazy searching where my code failed ... I was able to isolated this strange behaviour. Look at what hapens when substracting -200 days


NSDate *now = [NSDate date]; //now is 2013-07-19

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"YYYY-MM-dd"];

NSDate *newDate1 = [now  dateByAddingTimeInterval:60*60*24*-199];
newDateTmp=[format stringFromDate:newDate1];
NSLog(@"now:%@ newDateTmp:%@",now,newDateTmp);

newDate1 = [now  dateByAddingTimeInterval:60*60*24*-200];
newDateTmp=[format stringFromDate:newDate1];
NSLog(@"now:%@ newDateTmp:%@",now,newDateTmp);

newDate1 = [now  dateByAddingTimeInterval:60*60*24*-201];
newDateTmp=[format stringFromDate:newDate1];
NSLog(@"now:%@ newDateTmp:%@",now,newDateTmp);

newDate1 = [now  dateByAddingTimeInterval:60*60*24*-365];
newDateTmp=[format stringFromDate:newDate1];
NSLog(@"now:%@ newDateTmp:%@",now,newDateTmp);

logs:

2013-07-19 15:58:46.123 Vendes[2927:907] now:2013-07-19 13:58:46 +0000 newDateTmp:2013-01-01 // This is OK

2013-07-19 15:58:46.124 Vendes[2927:907] now:2013-07-19 13:58:46 +0000 newDateTmp:2013-12-31 // This is INCORRECT!!!! Look at the YEAR

2013-07-19 15:58:46.125 Vendes[2927:907] now:2013-07-19 13:58:46 +0000 newDateTmp:2012-12-30 // This is OK

2013-07-19 15:58:46.127 Vendes[2927:907] now:2013-07-19 13:58:46 +0000 newDateTmp:2012-07-19 // This is OK


I guess it will hapopen also tomorrow substracting 201 .. ?? :)

Any idea?

Thks

PS. I solved it using

NSDate *newDate1= [NSDate dateWithTimeInterval:60*60*daysToAdd sinceDate:now];

that works for any daysToAdd value.

Was it helpful?

Solution

It is not a bug. The format you use is wrong. It should be

@"yyyy-MM-dd"

with lower-cased y


More information on upper-cased Y :

Y - Year (in "Week of Year" based calendars). This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top