0

我向 NSDate 添加了一个类别,如下所示:

@interface NSDate (ElapsedDays)

-(unsigned long) elapsedDays: (NSDate *) theDate;

@end

@implementation NSDate (ElapsedDays)

-(unsigned long) elapsedDays:(NSDate *)theDate
{
  self.[???]
}

@end

我主要声明 NSDate 如下:

NSDate *today=[NSDate date];

现在在elapsedDays实现中,我如何访问NSDate初始化的日期?

4

1 回答 1

2

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]);
    }
}
于 2013-01-01T08:38:42.360 回答