How can I calculate the difference between two dates?

后端 未结 9 1384
渐次进展
渐次进展 2020-11-28 02:27

How can I calculate the days between 1 Jan 2010 and (for example) 3 Feb 2010?

9条回答
  •  情书的邮戳
    2020-11-28 03:13

    If you want all the units, not just the biggest one, use one of these 2 methods (based on @Ankish's answer):

    Example output: 28 D | 23 H | 59 M | 59 S

    + (NSString *) remaningTime:(NSDate *)startDate endDate:(NSDate *)endDate
    {
        NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
        NSDateComponents *components = [[NSCalendar currentCalendar] components:units fromDate: startDate toDate: endDate options: 0];
        return [NSString stringWithFormat:@"%ti D | %ti H | %ti M | %ti S", [components day], [components hour], [components minute], [components second]];
    }
    
    + (NSString *) timeFromNowUntil:(NSDate *)endDate
    {
        return [self remaningTime:[NSDate date] endDate:endDate];
    }
    
    

提交回复
热议问题