我正在使用 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/