这是一个应该满足您的条件的示例类:
主文件
#import <Foundation/Foundation.h>
#import "DateChecker.h"
int main(int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Specify a period in days
NSInteger period = 2;
// Set the start/end/current days. These can be retrieved from a database or elsewhere
NSDate *startDate = [NSDate dateWithString:@"2012-04-12 00:00:00 +0000"];
NSDate *endDate = [NSDate dateWithString:@"2012-04-20 00:00:00 +0000"];
NSDate *currentDate = [NSDate dateWithString:@"2012-04-14 00:00:00 +0000"];
// Actually do the checking. This could alternatively be offloaded to a function in DateChecker
if([DateChecker date:currentDate isBetweenDate:startDate andDate:endDate])
{
if([DateChecker date:currentDate fallsOnStartDate:startDate withInterval:period])
{
NSLog(@"The date %@ falls in the specified date period & is on the interval date.", currentDate);
}
else
{
NSLog(@"The date %@ falls in the specified date period & is NOT on the interval date.", currentDate);
}
}
else
{
NSLog(@"The date %@ does not fall in the specified date period.", currentDate);
}
[pool release];
return 0;
}
日期检查器.h
#import <Foundation/Foundation.h>
@interface DateChecker : NSObject
{
}
+ (BOOL)date:(NSDate*)date fallsOnStartDate:(NSDate*)beginDate withInterval:(NSInteger)daysInterval;
+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate;
@end
日期检查器.m
#import "DateChecker.h"
@implementation DateChecker
+ (BOOL)date:(NSDate*)date fallsOnStartDate:(NSDate*)beginDate withInterval:(NSInteger)daysInterval
{
NSDateComponents *components;
NSInteger days;
// Get the number of days since the start date
components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit fromDate: beginDate toDate: date options: 0];
days = [components day];
// If the number of days passed falls on the interval, then retrun YES
if(days % daysInterval == 0)
{
return YES;
}
else
{
return NO;
}
}
+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
if ([date compare:beginDate] == NSOrderedAscending)
return NO;
if ([date compare:endDate] == NSOrderedDescending)
return NO;
return YES;
}
@end
这应该让您了解如何编写一个可以处理您的要求的类。我将它作为命令行应用程序运行,它似乎工作正常。功能
+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
是从如何检查 NSDate 是否发生在其他两个 NSDate 之间慷慨地获得的。