How to get relative dates

How can I get relative dates in Objective-C?

If I have “today”, how can I find “yesterday”, “last week”, “last two weeks”, “month ago”, “two months ago”?

+3
source share
1 answer

So, if you have NSDate *today = [NSDate date];, you can use NSDateComponentsto get relative dates.

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];

Etc.

NSDateComponents NSCalendar ( options:). "28 ", "", "29 " "1 " . . .

+10

All Articles