Alex Tau Alex Tau - 1 year ago 99
iOS Question

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.

Answer Source

use dateByAddingTimeInterval method:

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


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

Hope it helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download