如何获得相对日期

Ali*_*Ali 3 objective-c relative-date

如何在Objective-C中获取相对日期?

如果我有"今天",我如何找到"昨天","上周","过去两周","一个月前","两个月前"?

Dav*_*ong 10

所以如果你有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];
Run Code Online (Sandbox Code Playgroud)

等等.

NSDateComponentsNSCalendar自动处理下溢和溢出(除非你用options:钻头将其关闭).因此,如果今天是"2月28日"并且您想要"明天",它将根据年份自动选择"2月29日"或"3月1日".它太酷了.这也是进行日期操作的唯一正确方法.