2013-08-06 54 views
0
NSDate *today = [NSDate date]; 
NSDate *pastSevenDays = [today dateByAddingTimeInterval:-7*24*60*60]; 
NSLog(@"7 days ago: %@",pastSevenDays); 

NSDate *pastFourteenDays = [today dateByAddingTimeInterval:-14*24*60*60]; 
NSLog(@"14 days ago: %@",pastFourteenDays); 

NSDate *pastThirtyDays = [today dateByAddingTimeInterval:-30*24*60*60]; 
NSLog(@"30 days ago: %@",pastThirtyDays); 

NSDate *pastSixtyDays = [today dateByAddingTimeInterval:-60*24*60*60]; 
NSLog(@"60 days ago: %@",pastSixtyDays); 

NSDate *pastNintyDays = [today dateByAddingTimeInterval:-90*24*60*60]; 
NSLog(@"90 days ago: %@",pastNintyDays); 

登錄:的NSDate:日期介於兩個日期之間

2013-08-05 21:47:11.684 Time[29542:c07] 7 days ago: 2013-07-29 07:00:00 +0000 
2013-08-05 21:47:11.685 Time[29542:c07] 14 days ago: 2013-07-22 07:00:00 +0000 
2013-08-05 21:47:11.685 Time[29542:c07] 30 days ago: 2013-07-06 07:00:00 +0000 
2013-08-05 21:47:11.685 Time[29542:c07] 60 days ago: 2013-06-06 07:00:00 +0000 
2013-08-05 21:47:11.685 Time[29542:c07] 90 days ago: 2013-05-07 07:00:00 +0000 

你如何檢查是否一個NSDate變量是兩個日期之間?即:

NSDate *dateToCompare = //a date in NSDate Format 


if (dateToCompare is on or before pastSevenDays) && (datetoCompare is after pastFourteenDays) 
{ 
\\ Do the following 
} 

if (dateToCompare is on or before pastFourteenDays) && (datetoCompare is after pastThirtyDays) 
{ 
\\ Do the following 
} 

// and so forth... 

回答

0

看來這應該做你所需要的。

if ([dateToCompare laterDate:pastSevenDays] == dateToCompare) 
{ 
    // dateToCompare is less than 7 days ago 
} 
else if ([dateToCompare laterDate:pastFourteenDays] == dateToCompare) 
{ 
    // dateToCompare is more than 7 days ago, but less than 14 days ago 
} 
else if ([dateToCompare laterDate:pastThirtyDays] == dateToCompare) 
{ 
    // dateToCompare is more than 14 days ago, but less than 30 days ago 
} 
+0

這至少與「可能的重複」的答案不同,但我仍然更願意直接比較:'。 –