如何获得当前日期的前7天?

sur*_*her 0 iphone xcode objective-c

我正在开展一个项目,我需要在用户从日期选择器中选择的特定日期之前7天设置警报.

我使用以下代码从用户获取日期

NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateStyle:NSDateFormatterFullStyle];
NSString *dateStr = [NSString stringWithFormat:@"%@",[df stringFromDate:datePickerObj.date]];
[df release];
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我如何获得所选日期之前7天的日期.提前致谢

Nik*_*rov 8

使用dateByAddingComponents:toDate:options:,像这样:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = -7;
NSDate *earlierDate = [calendar dateByAddingComponents:components
    toDate:datePickerObj.date options:0];
Run Code Online (Sandbox Code Playgroud)