iOS可读字符串/日期格式化程序
我试图以可读的格式显示2个日期的差异。 从我下面的代码中可以看到,有很多if-else闭包。 如果elses是对的,有什么格式化程序或我的方法吗iOS可读字符串/日期格式化程序,ios,objective-c,nsstring,nsdateformatter,readable,Ios,Objective C,Nsstring,Nsdateformatter,Readable,我试图以可读的格式显示2个日期的差异。 从我下面的代码中可以看到,有很多if-else闭包。 如果elses是对的,有什么格式化程序或我的方法吗 NSCalendar *c = [NSCalendar currentCalendar]; NSDateComponents *components = [c components:(NSCalendarUnitMonth | NSCalendarUnitDay) from
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"
使用以下类别的
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"
使用以下类别的
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"
您可以使用
你可以用它
您可以将
nsdatecomponentsformter
与SpellOut
单元样式一起使用,它可以输出类似“一小时十分钟”的内容
查看此处以了解详细信息:您可以使用
nsdatecomponents格式表
和拼写
单元样式,该格式可以输出类似“一小时十分钟”的内容
查看此处了解详细信息: