2011-12-07 54 views

回答

-1

假設你不關心DST,

NSDate* pastDate = [NSDate dateWithTimeIntervalSinceNow:-2*7*24*60*60]; 

// Get the date which is exactly 2 weeks (14 days) ago. 
+0

希望夏令時沒有變化。 :-)最好使用'NSDateComponents'和'NSCalendar',讓Apple處理所有的角落案例。 – zaph

6

了我的頭頂部:

NSDate *today = [NSDate date]; 
NSDateComponents *dc = [[[NSDateComponents alloc] init] autorelease]; 
[dc setDay:-14]; 
NSCalendar *cal = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; 
NSDate *pastDate = [cal dateByAddingComponents:dc toDate:today options:0]; 
3
NSDate *today = [NSDate date]; 
NSLog(@"today: %@",today); 

NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; 
[dateComponents setWeek:-2]; 
NSCalendar *currentCalendar = [NSCalendar currentCalendar]; 
NSDate *pastDate = [currentCalendar dateByAddingComponents:dateComponents toDate:today options:0]; 
NSLog(@"pastDate: %@",pastDate); 

的NSLog輸出:

today: 2011-12-07 11:52:15 +0000 
pastDate: 2011-11-23 11:52:15 +0000 

這個例子使用ARC。

相關問題