如何獲得相對日期
回答
所以,如果你有一個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日」。它太酷了。這也是做日期操作的唯一正確方式。
周不會返回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
也NSCalendar取決於ipad日曆,或它總是georgean – Ali 2011-03-22 08:56:48
此代碼不起作用;它總是返回最初的日期。我不得不使用'dateByAddingComponents:toDate:options:'。我假設所有對這個答案的讚揚都來自沒有真正測試代碼的人。 – titaniumdecoy 2012-09-27 21:14:55
真的不知道你在問什麼。 – 2011-03-21 16:56:45