如何在 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 日”。它太酷了。这也是进行日期操作的唯一正确方法。