1

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

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

        }

但这不会检查 10 月 15 日是否位于 10 月 14 日至 20 日之间。而是检查整个日期。那么,我将如何实现这一点。提前谢谢。

4

3 回答 3

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
}
于 2012-09-18T04:24:36.570 回答
3

其中date1 = 2011-10-14 和date2 =2011-10-20 并且date是您要检查的日期。

做这个

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

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

于 2012-09-18T04:33:57.733 回答
1

比较->

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!");
}
于 2012-09-18T04:53:14.883 回答