gpt4 book ai didi

cocoa - 如何在 Cocoa 中格式化时间间隔?

转载 作者:行者123 更新时间:2023-12-03 16:09:46 25 4
gpt4 key购买 nike

我正在寻找一个格式化时间间隔的类,如下所示:

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/

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