Search code examples
objective-ciosnsdate

Subtract 7 days from current date


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.


Solution

  • use dateByAddingTimeInterval method:

    NSDate *now = [NSDate date];
    NSDate *sevenDaysAgo = [now dateByAddingTimeInterval:-7*24*60*60];
    NSLog(@"7 days ago: %@", sevenDaysAgo);
    

    output:

    7 days ago: 2012-04-11 11:35:38 +0000