我有两个日期,开始日期和结束日期。现在我想检查我当前的日期是否在这两个日期之间。
例如开始日期:2013-09-17 15:05:00 +0000 结束日期:013-09-25 17:05:00 +0000
NSComparisonResult result,restult2;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
result = [currentDate compare:startDate]; // comparing two dates
result2 = [currentDate compare:endDate]; // comparing two dates
if(result==NSOrderedAscending && result==NSOrderedDescending)
{
NSLog(@"Between the StartDate and Enddate");
}
这是我写的一个方法:
- (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime {
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate
interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate
interval:NULL forDate:toDateTime];
NSDateComponents *differenceComponents = [calendar components:NSDayCalendarUnit
fromDate:fromDate
toDate:toDate
options:0];
return [differenceComponents day];
}
它计算两个日期之间的天数。您可以使用它来计算间隔,然后再次使用它来计算第三个日期(您要检查的日期)是否在您感兴趣的间隔内。
NSDateFormatter *formate = [[NSDateFormatter alloc] init];
[formate setDateFormat:@"dd-MM-yyyy"];--> this line first set type of formate to compare
NSDate *date1 = [formate dateFromString:@"1-5-2010"];-->first date
NSDate *date2 = [formate dateFromString:@"7-5-2010"];-->second date
//difference between dates in miliseconds
NSTimeInterval interval = [date1 timeIntervalSinceDate:date2];
//compare two dates
NSComparisonResult result = [date1 compare:date2];
switch (result)
{
case NSOrderedAscending: NSLog(@"%@ is greater than %@", date2, date1); break;
case NSOrderedDescending: NSLog(@"%@ is less %@", date2, date1); break;
case NSOrderedSame: NSLog(@"%@ is equal to %@", date2, date1); break;
default: NSLog(@"erorr dates %@, %@", date2, date1); break;
}