Objective c 如何在objc中比较时间

Objective c 如何在objc中比较时间,objective-c,nsdate,Objective C,Nsdate,我想要一个倒计时,显示日期、小时、M和S。一秒钟叫做一次 - (void)changetime { NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象 NSDate *today = [NSDate date];//得到当前时间 unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalend

我想要一个倒计时,显示日期、小时、M和S。一秒钟叫做一次

- (void)changetime {     

    NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象                 
    NSDate *today = [NSDate date];//得到当前时间

    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *weekdayComponents =[cal components:(unitFlags) fromDate:self.overDate]; 
    NSDate *todate = [cal dateFromComponents:weekdayComponents]; 
    NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:todate options:0];

    NSInteger days=[d year]*365+[d month]*31+[d day];
    if ([self.overDate earlierDate:[NSDate date]]==self.overDate) {
        [myTimer invalidate];
        myTimer=nil;
        self.labdate.text = [NSString stringWithFormat:@"%d天%d时%d分%d秒",days, [d hour], [d minute], [d second]];
        return;
    }    
    self.labdate.text = [NSString stringWithFormat:@"%d天%d时%d分%d秒",days, [d hour], [d minute], [d second]];     
}

myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changetime) userInfo:nil repeats:YES];

self.overDate=[wedding date];//this is a future time

以下行应引起您的报警:

NSInteger days=[d year]*365+[d month]*31+[d day];
一年中只有365天,占公历时间的75%。将近50%的月份在日历中没有31天。查看Apple文档中的部分,它告诉您,如果您在
组件:fromDate:toDate:options:
调用中请求Day组件,而没有更大的内容,那么您将得到您需要考虑日历的天数