0

我正在尝试以可读格式显示 2 个日期的差异。从我下面的代码中可以看出,有很多 if-else 闭包。是否有任何格式化程序或我的 if-elses 方式是正确的?

NSCalendar *c = [NSCalendar currentCalendar];
NSDateComponents *components = [c components:(NSCalendarUnitMonth | NSCalendarUnitDay)
                                        fromDate:startDate
                                          toDate:endDate
                                         options:0];

NSString *leftTimeStr = @"";
if (components.month == 0) {
    if (components.day == 1) {
        leftTimeStr = @"after 1 day";
    }
    else if (components.day > 1) {
        leftTimeStr = [NSString stringWithFormat:@"after %ld days", (long)components.day];
    }
}
else if (components.month == 1) {
    if (components.day == 0) {
        leftTimeStr = @"after 1 month";
    }
    else if (components.day == 1) {
        leftTimeStr = @"after 1 month 1 day";
    }
    else if (components.day > 1) {
        leftTimeStr = [NSString stringWithFormat:@"after 1 month %ld days", (long)components.day];
    }
}
else if (components.month > 1) {
    if (components.day == 0) {
        leftTimeStr = [NSString stringWithFormat:@"after %ld months", (long)components.month];
    }
    else if (components.day == 1) {
        leftTimeStr = [NSString stringWithFormat:@"after %ld months 1 day", (long)components.month];
    }
    else if (components.day > 1) {
        leftTimeStr = [NSString stringWithFormat:@"after %ld months %ld days", (long)components.month, (long)components.day];
    }
}

结果leftTimeStr字符串应类似于以下内容之一:

"after 5 months 22 days",
"after 5 months 1 day",
"after 5 months",
"after 1 month 22 days",
...
"after 22 days",
"after 1 day"
4

3 回答 3

2

为此,您可以使用NSDateComponentsFormatter.

NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
[formatter setAllowedUnits:NSCalendarUnitMonth | NSCalendarUnitDay];
formatter.maximumUnitCount = 2;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
NSString *difference = [formatter stringFromDate:startDate toDate:endDate];
于 2017-01-31T06:29:39.227 回答
1

您可以使用可以输出如下内容NSDateComponentsFormatterSpellOut单位样式:“一小时,十分钟”。

在此处查看详细信息:http: //nshipster.com/nsformatter/#nsdatecomponentsformatter

于 2017-01-31T06:30:02.353 回答
1

使用以下类别类NSDate

NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:0];
NSString *ago = [date timeAgo];
NSLog(@"Output is: \"%@\"", ago);
2011-11-12 17:19:25.608 Proj[0:0] Output is: "41 years ago"

来源自 GitHub

于 2017-01-31T06:23:06.517 回答