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

时间:2017-01-31 06:18:33

标签: ios objective-c nsstring nsdateformatter readable

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

3 个答案:

答案 0 :(得分: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"

Source from GitHub

答案 1 :(得分:1)

为此,您可以使用NSDateComponentsFormatter

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

答案 2 :(得分:1)

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

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