检查iPhone中的日期是否介于两天之间

时间:2012-09-18 04:07:22

标签: iphone ios nsdateformatter date-comparison

我知道如何比较日期。在我的情况下,让Date1 = 2011-10-14& Date2 = 2011-10-20。我想检查10月15日是否在Date1和Date2之间。我使用以下代码:

if ( [date compare:Date1] == NSOrderedDescending && [date compare:Date2] == NSOrderedAscending) {   
            //write codes

        }

但是这不会检查10月14日到20日之间是否存在第15天。它会检查整个日期。那么,我将如何实现这一点。 Thnx提前。

3 个答案:

答案 0 :(得分:4)

我希望以下代码能为您提供帮助。假设你有Date1和Date2,

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger desiredComponents = (NSDayCalendarUnit | NSMonthCalendarUnit);


NSDateComponents *firstComponents = [calendar components:desiredComponents fromDate:Date1];
NSDateComponents *secondComponents = [calendar components:desiredComponents fromDate:Date2];

NSDate *firstWOYear = [calendar dateFromComponents:firstComponents];
NSDate *SecondWOYear = [calendar dateFromComponents:secondComponents];

NSComparisonResult result = [firstWOYear compare:SecondWOYear];
if (result == NSOrderedAscending) {
    //Date1 is before Date2
} else if (result == NSOrderedDescending) {
    //Date1 is after Date2
}  else {
    //Date1 is the same day/month as Date2
}

答案 1 :(得分:3)

date1 = 2011-10-14且 date2 = 2011-10-20,日期是您要检查的日期。

这样做

if([date timeIntervalSince1970] >= [date1 timeIntervalSince1970] && [date timeIntervalSince1970] <= [date2 timeIntervalSince1970])
{
    NSLog(@"%@ lies between and including %@ and %@",date,date1,date2);
   // if you just wanna check for between (not including) two dates just remove the equal signs above in condition check
}
else
    NSLog(@"%@ does not lie between %@ and %@",date,date1,date2);

上面的代码将检查日期是否在给定的两个极端日期之间,但是如果您只想检查(但不包括)极端日期,那么只需从条件检查中删除等号。

答案 2 :(得分:1)

比较 - &gt;

NSString *dateString1 = @"2011-10-14";
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"yyyy-MM-dd";

NSDate *date1 = [formatter dateFromString:dateString1];

NSString *dateString2 = @"2011-10-20";    
NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
formatter2.dateFormat = @"yyyy-MM-dd";

NSDate *date2 = [formatter2 dateFromString:dateString2];


NSString *dateString3 = @"2011-10-15";
NSDateFormatter *formatter3 = [[NSDateFormatter alloc]init];
formatter3.dateFormat = @"yyyy-MM-dd";

NSDate *date3 = [formatter3 dateFromString:dateString3];

if ([date3 compare:date1] == NSOrderedDescending && [date3 compare:date2] == NSOrderedAscending) 
{
    NSLog(@"%@ lies b/w %@ and %@",dateString3,dateString1,dateString2);
}
else
{
    NSLog(@"Doesn't lie!");
}