我正在尝试以可读格式显示 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"