我試圖以可讀格式顯示2日期的差異。正如你可以從我的下面的代碼看到有很多if-else關閉。 有沒有什麼格式化工具或我的方式,如果else是正確的?iOS可讀字符串/日期格式化程序
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"
雖然此鏈接可以回答這個問題,最好是在這裏有答案的主要部件,並提供鏈接以供參考。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/15053385) –
好的,謝謝@FranzGleichmann。我會更新我的答案 – KKRocks