【发布时间】:2011-07-19 20:22:22
【问题描述】:
如何在 Objective-C 中获取相对日期?
如果我有“今天”,如何找到“昨天”、“上周”、“过去两周”、“一个月前”、“两个月前”?
【问题讨论】:
-
真的不知道你在问什么。
如何在 Objective-C 中获取相对日期?
如果我有“今天”,如何找到“昨天”、“上周”、“过去两周”、“一个月前”、“两个月前”?
【问题讨论】:
因此,如果您有NSDate *today = [NSDate date];,那么您可以使用NSDateComponents 来获取相对日期。
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateComponents *yesterdayComponents = [[NSDateComponents alloc] init];
[yesterdayComponents setDay:-1];
NSDate *yesterday = [calendar dateByAddingComponents:yesterdayComponents toDate:today options:0];
[yesterdayComponents release];
NSDateComponents *twoWeeksAgoComponents = [[NSDateComponents alloc] init];
[twoWeeksAgoComponents setWeek:-2];
NSDate *twoWeeksAgo = [calendar dateByAddingComponents:twoWeeksAgoComponents toDate:today options:0];
[twoWeeksAgoComponents release];
等等
NSDateComponents 和 NSCalendar 自动处理下溢和上溢(除非您使用 options: 位将其关闭)。因此,如果今天是“2 月 28 日”而您想要“明天”,它将根据年份自动选择“2 月 29 日”或“3 月 1 日”。它太酷了。这也是进行日期操作的唯一正确方法。
【讨论】:
dateByAddingComponents:toDate:options:。我假设对这个答案的所有支持都来自没有实际测试代码的人。