elapsedDays
消息的接收者self
在方法实现范围内。
例如:
#import <Foundation/Foundation.h>
@interface NSDate (ElapsedDays)
- (NSInteger)elapsedDaysSinceDate:(NSDate *)theDate;
@end
@implementation NSDate (ElapsedDays)
static const NSInteger SecondsPerDay = 86400;
- (NSInteger)elapsedDaysSinceDate:(NSDate *)theDate {
NSTimeInterval interval = [self timeIntervalSinceDate:theDate];
return interval/SecondsPerDay;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMddyyyy"];
NSDate *date1 = [dateFormatter dateFromString:@"01012012"];
NSDate *date2 = [dateFormatter dateFromString:@"12312012"];
printf("Date difference = %ld",[date2 elapsedDaysSinceDate:date1]);
}
}
打印Date difference = 365
到控制台。
编辑(使用公历计算)
#import <Foundation/Foundation.h>
@interface NSDate (ElapsedDays)
- (NSInteger)elapsedDaysSinceDate:(NSDate *)theDate;
@end
@implementation NSDate (ElapsedDays)
- (NSInteger)elapsedDaysSinceDate:(NSDate *)theDate {
NSTimeInterval interval = [self timeIntervalSinceDate:theDate];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSDayCalendarUnit
fromDate:theDate
toDate:self
options:0];
return [components day];
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMddyyyy"];
NSDate *date1 = [dateFormatter dateFromString:@"01012012"];
NSDate *date2 = [dateFormatter dateFromString:@"12312012"];
printf("Date difference = %ld",[date2 elapsedDaysSinceDate:date1]);
}
}