作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在寻找一个格式化时间间隔的类,如下所示:
1 hour 3 minutes2 hours 5 minutes 12 seconds5 days 2 hours
是否有任何内置或库支持这种时间间隔格式?
我想过自己做,但是有各种各样的问题:
最佳答案
一个老问题,但是对于任何偶然发现这个问题的人,请查看NSDateComponentsFormatter
。
例如,这是我的 DejalFoundationCategories 中的一个 NSDate
类别方法开源项目:
+ (NSString *)dejal_relativeStringForTimeInterval:(NSTimeInterval)timeInterval style:(NSDateComponentsFormatterUnitsStyle)unitsStyle maximumUnits:(NSInteger)maximumUnits keepZero:(BOOL)keepZero defaultValue:(NSString *)defaultValue;
{
// If more than 10 years, assume distant past or future:
if (abs(timeInterval) > 60 * 60 * 24 * 365 * 10)
{
return defaultValue;
}
NSDateComponentsFormatter *formatter = [NSDateComponentsFormatter new];
formatter.unitsStyle = unitsStyle;
formatter.maximumUnitCount = maximumUnits;
if (keepZero)
{
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropLeading | NSDateComponentsFormatterZeroFormattingBehaviorDropMiddle;
}
else
{
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropAll;
}
return [formatter stringFromTimeInterval:timeInterval];
}
关于cocoa - 如何在 Cocoa 中格式化时间间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1508620/
我是一名优秀的程序员,十分优秀!