2011-03-21 81 views
3

我怎樣才能在Objective-C相對日期?如何獲得相對日期

如果我有「今天」,如何找到「昨天」,「上週」,「上兩個星期」,「一個月前」,「兩個月前」?

+0

真的不知道你在問什麼。 – 2011-03-21 16:56:45

回答

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

等等

NSDateComponentsNSCalendar手柄溢和自動溢出(除非你用options:位將其關閉)。因此,如果今天是「2月28日」,而您想要「明天」,則根據年份自動選擇「2月29日」或「3月1日」。它太酷了。這也是做日期操作的唯一正確方式

+0

周不會返回corrrectly \t NSDateComponents * TwoWeeksAgoComponents = [組分複製]; \t [TwoWeeksAgoComponents setWeek:[TwoWeeksAgoComponents周] -2]; \t的NSDate * TwoWeeksAgo = [日曆dateFromComponents:TwoWeeksAgoComponents]; \t NSLog([formatter stringFromDate:TwoWeeksAgo]); \t [TwoWeeksAgoComponents發佈]; – Ali 2011-03-22 08:21:52

+0

也NSCalendar取決於ipad日曆,或它總是georgean – Ali 2011-03-22 08:56:48

+0

此代碼不起作用;它總是返回最初的日期。我不得不使用'dateByAddingComponents:toDate:options:'。我假設所有對這個答案的讚揚都來自沒有真正測試代碼的人。 – titaniumdecoy 2012-09-27 21:14:55