Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract 7 days from current date

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


If you're running at least iOS 8 or OS X 10.9, there's an even cleaner way:

NSDate *sevenDaysAgo = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay
                                                                value:-7
                                                               toDate:[NSDate date]
                                                              options:0];

Or, with Swift 2:

let sevenDaysAgo = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -7,
    toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))

And with Swift 3 and up it gets even more compact:

let sevenDaysAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date())

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

Hope it helps


Swift 3

Calendar.current.date(byAdding: .day, value: -7, to: Date())