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

时间:2012-08-08 07:30:00

标签: iphone objective-c xcode

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

我使用以下代码从用户

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

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

1 个答案:

答案 0 :(得分: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];
相关问题