gpt4 book ai didi

iOS 可读字符串/日期格式化程序

转载 作者:行者123 更新时间:2023-11-28 18:50:35 24 4
gpt4 key购买 nike

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

最佳答案

为此你可以使用 NSDateComponentsFormatter .

NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
[formatter setAllowedUnits:NSCalendarUnitMonth | NSCalendarUnitDay];
formatter.maximumUnitCount = 2;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
NSString *difference = [formatter stringFromDate:startDate toDate:endDate];

关于iOS 可读字符串/日期格式化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41950893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com