Subtract 7 days from current date

Alex Tau picture Alex Tau · Apr 18, 2012 · Viewed 70.1k times · Source

It seems that I can't subtract 7 days from the current date. This is how i am doing it:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-7];
NSDate *sevenDaysAgo = [gregorian dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];

SevenDaysAgo gets the same value as the current date.

Please help.

EDIT: In my code I forgot to replace the variable which gets the current date with the right one. So above code is functional.

Answer

dymv picture dymv · Apr 22, 2012

code:

NSDate *currentDate = [NSDate date];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:-7];
NSDate *sevenDaysAgo = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(@"\ncurrentDate: %@\nseven days ago: %@", currentDate, sevenDaysAgo);
[dateComponents release];

output:

currentDate: 2012-04-22 12:53:45 +0000
seven days ago: 2012-04-15 12:53:45 +0000

And I'm fully agree with JeremyP.

BR.
Eugene