DateDiff 在 Objective-C 中的实现

/* dateDiff 方法实现 */ 

+(NSDateComponents *) dateDiff:(NSDate *) fromDate toDate:(NSDate *) toDate
{
    NSCalendar *sysCalendar = [NSCalendar currentCalendar];
    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |
                              NSDayCalendarUnit | NSHourCalendarUnit |
                              NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *compInfo = [sysCalendar components:unitFlags
                                              fromDate:fromDate
                                              toDate:toDate
                                              options:0];
    return compInfo;
}

/* dateDiff 调用示例 */ 

- (void) demo
{
    NSDate *date1 = [[NSDate alloc] init];
    NSDate *date2 = [[NSDate alloc] initWithTimeIntervalSinceNow:86400];

    NSDateComponents *diffInfo =[KRUtils dateDiff:date1 toDate:date2];
    NSLog(@"相差 %d天%02d小时%02d分钟%02d秒", [diffInfo day],
                                              [diffInfo hour],
                                              [diffInfo minute],
                                              [diffInfo second]);
    //输出结果:“相差 1天00小时00分钟00秒” 
}

posted on 2012-10-29 15:32  Solitary  阅读(174)  评论(0编辑  收藏  举报

导航