我似乎无法从当前日期减去 7 天。我就是这样做的:
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 获得与当前日期相同的值。
请帮忙。
编辑:在我的代码中,我忘记用正确的日期替换获取当前日期的变量。所以上面的代码是正常的。
最佳答案
代码:
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];
输出:
currentDate: 2012-04-22 12:53:45 +0000
seven days ago: 2012-04-15 12:53:45 +0000
我完全同意 JeremyP 的观点。
BR.
尤金
关于objective-c - 从当前日期减去 7 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10209427/