how can I get relative dates in Objective-C?
If I have "today", how do I find "yesterday", "last week", "last two weeks", "one month ago", "two months ago"?
how can I get relative dates in Objective-C?
If I have "today", how do I find "yesterday", "last week", "last two weeks", "one month ago", "two months ago"?
So if you have an NSDate *today = [NSDate date];
, then you can use NSDateComponents
to 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
and NSCalendar
handle underflowing and overflowing automatically (unless you turn it off with the options:
bit). So if today is "28 February" and you want "tomorrow", it will automatically choose either "29 February" or "1 March" depending on the year. It's pretty cool. This is also the only proper way of doing date manipulation.