ElapsedDays.h头文件
#import <Foundation/Foundation.h>
@interface NSCalendarDate (ElapsedDays)
-(unsigned long) numberOfElapsedDays: (NSCalendarDate *) theDate;
@end
ElapsedDays.m源文件
#import "ElapsedDays.h"
#define IS_LEAP_YEAR(y) (y % 4 == 0 && y % 100 != 0 || y % 400 == 0)
@implementation NSCalendarDate (ElapsedDays)
-(unsigned long) numberOfElapsedDays: (NSCalendarDate *) theDate
{
int years, months, days;
unsigned long totDays = 0;
NSCalendarDate *minDate, *maxDate;
int maxDateYear, maxDateMonth, minDateYear, minDateMonth;
int dayPerMonth[12] = {31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (self < theDate) {
minDate = self;
maxDate = theDate;
} else {
minDate = theDate;
maxDate = self;
}
[maxDate years: &years
months: &months
days: &days
hours: NULL
minutes: NULL
seconds: NULL
sinceDate: minDate
];
minDateYear = [minDate yearOfCommonEra];
maxDateYear = [maxDate yearOfCommonEra];
minDateMonth = [minDate monthOfYear];
maxDateMonth = [maxDate monthOfYear];
int y = minDateYear;
int m = minDateMonth;
// loop as long as the maxDate is not reached
while (!(y == maxDateYear && m == maxDateMonth))
{
if (m != 2)
{
totDays += dayPerMonth[m - 1];
}
else
{
if IS_LEAP_YEAR(y)
{
totDays += 29;
}
else
{
totDays += 28;
}
}
// calculate the next date in term of year and month
if (m == 12)
{
y++;
m = 1;
}
else
{
m++;
}
}
totDays += days;
return totDays;
}
@end
test.m源文件
#import <Foundation/Foundation.h>
#import "ElapsedDays.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSCalendarDate *thisDate = [[NSCalendarDate alloc] initWithYear: 1999
month: 10
day: 14
hour: 0
minute: 0
second: 0
timeZone: nil
];
NSCalendarDate *thatDate = [[NSCalendarDate alloc] initWithYear: 2010
month: 10
day: 14
hour: 0
minute: 0
second: 0
timeZone: nil
];
unsigned long days = [thisDate numberOfElapsedDays: thatDate];
NSLog(@"\nBetween the\n %@ \nand the\n %@ \nthere are %lu days.", thisDate , thatDate, days);
[pool drain];
return 0;
}