首页 > 解决方案 > 获取两个日期之间的差异?

问题描述

我在 24 小时内有两个日期,例如 (dd-MMM-yyyy HH:mm)。我想知道这两个日期之间的区别。

我的代码:这只是获取日期,我还想要天数和剩余时间(以小时为单位)。(如 6 天 5 小时)

    NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
    int numberOfDays = secondsBetween / 86400;
    NSLog(@"There are %d days in between the two dates.", numberOfDays);

标签: iosobjective-ccocoa-touchnsdatensdateformatter

解决方案


NSDateComponentsFormatter可以这样做

NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
NSLog(@"%@", [formatter stringFromTimeInterval:secondsBetween]);

其他款式见NSDateComponentsFormatterUnitsStyle


推荐阅读