surendher
surendher

Reputation: 1378

How to get the 7 days previous date of current date?

I am working on a project where i need to set an alarm on 7 days before particular date the user has selected from date picker.

I used the following code to get the date from user

NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateStyle:NSDateFormatterFullStyle];
NSString *dateStr = [NSString stringWithFormat:@"%@",[df stringFromDate:datePickerObj.date]];
[df release];

Can any one please tell me how to get the date of 7 days previous to the selected date. Thanks in advance

Upvotes: 0

Views: 752

Answers (1)

Nikita Pestrov
Nikita Pestrov

Reputation: 5966

Use dateByAddingComponents:toDate:options:, like this:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = -7;
NSDate *earlierDate = [calendar dateByAddingComponents:components
    toDate:datePickerObj.date options:0];

Upvotes: 8

Related Questions