objective-c - 从当前日期减去 7 天

我似乎无法从当前日期减去 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.
尤金

https://stackoverflow.com/questions/10209427/

相关文章:

ios - 如何在 UITextView 中禁用复制、剪切、选择、全选

ios - 检测到约束模糊地表明高度为零的情况

ios - 如果没有 Table View 结果,在屏幕上显示 "No Results"

ios - 添加一个简单的 UIAlertView

ios - 如何以编程方式检查 iOS 应用程序中是否存在键盘?

ios - Swift - 使用哪些类型? NSString 或字符串

iphone - ${EXECUTABLE_NAME} 和 ${PRODUCT_NAME} 在哪里定

iphone - 代码设计错误 : Certificate identity appearing t

ios - 从 iPhone 上的 NSString 中删除 HTML 标签

ios - 带有两种不同颜色文本的 UILabel