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



我正在尝试以可读格式显示 2 日期的差异。正如你从下面的代码中看到的,有很多if-else闭包。是否有任何类型的格式化程序或我的"如果-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];

您可以将NSDateComponentsFormatterSpellOut单位样式一起使用,该样式可以输出类似"一小时,十分钟"的内容。

详情请点击此处:http://nshipster.com/nsformatter/#nsdatecomponentsformatter

使用以下

类别类 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

相关内容

  • 没有找到相关文章

最新更新