objective-c - 如果时间为零,如何使 NSDateFormatter 不包括时间?

标签 objective-c ios time nsdate nsdateformatter

我正在使用 NSDateFormatter 来格式化持续时间 ( see here )。

我想使用这样的格式:“3 小时 15 分钟”。
这是我正在使用的格式字符串:@"H' 小时,'m' 分钟'"

问题是,对于短于一小时的持续时间,结果类似于“0 小时 35 分钟”。
在这种情况下,我只想显示“35 分钟”。

有没有办法告诉 NSDateFormatter 在没有小时的情况下根本不显示小时,或者我应该只使用 if 语句并手动构造字符串?

编辑:
我很清楚,这很容易通过几行额外的代码手动完成,这就是我过去的做法。我只是想知道格式化程序是否有足够的智慧来自行处理这个问题,因为这似乎是一个常见问题。

最佳答案

从 iOS 8.0 和 Mac OS X 10.10 (Yosemite) 开始,您可以使用 NSDateComponentsFormatter。因此,让我们将小时和分钟用作 allowedUnits(如您的示例中所示),将 NSDateComponentsFormatterZeroFormattingBehaviorDropLeading 用作 zeroFormattingBehavior 以减少零小时。示例:

NSTimeInterval intervalWithHours = 11700; // 3:15:00
NSTimeInterval intervalWithZeroHours = 2100; // 0:35:00
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorDropLeading;
NSString *string = [formatter stringFromTimeInterval:intervalWithHours];
NSString *stringWithoutHours = [formatter stringFromTimeInterval:intervalWithZeroHours];
NSLog(@"%@ / %@", string, stringWithoutHours);
// output: 3 hours, 15 minutes / 35 minutes

swift 5 版本:

let intervalWithHours: TimeInterval = 11700
let intervalWithZeroHours: TimeInterval = 2100
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
formatter.unitsStyle = .full
formatter.zeroFormattingBehavior = .dropLeading
if let string = formatter.string(from: intervalWithHours), let stringWithoutHours = formatter.string(from: intervalWithZeroHours) {
    print("\(string) / \(stringWithoutHours)")
    // output: "3 hours, 15 minutes / 35 minutes\n"
}

关于objective-c - 如果时间为零,如何使 NSDateFormatter 不包括时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12239019/

相关文章:

实时计算运行时差异

iphone - 在 iOS 上使用与核心数据的关系

ios - 我可以将 Touch ID 弹出窗口中的操作名称从 "Enter password"更改为 "Enter passcode"吗?

ios - <Application> 有超出允许时间的事件断言 - 仅限 iPhone 5S,适用于 iPhone 5、4s 和 4

iphone - UIButton 图像不会在 "for"循环中更改

ios - BLE 中央 iOS 应用应何时读取加密特征?

ios - 我可以为 SKSpriteNode 添加边框,类似于 UIView 吗?

ios - 核心数据关系未映射到 RESTkit

使用 CLOCK_MONOTONIC 的 Android(Linux) 正常运行时间

java - 如何在java中将时间四舍五入到最接近的15分钟