NSDate:日期位于两个日期之间

时间:2013-08-06 05:00:31

标签: objective-c ios6 nsdate

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

日志:

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...

1 个答案:

答案 0 :(得分: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
}