Swift DateComponentsFormatter删除前导零,但在Minutes位置至少保留一位数字 [英] Swift DateComponentsFormatter drop leading zeroes but keep at least one digit in Minutes place
问题描述
我在Swift中使用以下DateComponentsFormatter:
I am using the following DateComponentsFormatter in Swift:
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.hour, .minute, .second]
formatter.zeroFormattingBehavior = [.default]
这将产生类似于2:41(2分41秒)和08(8秒)的结果。但是,我想在Minutes位置至少保留一位数字,返回0:08而不是08。DateComponentsFormatter是否可能?我希望有一个返回本地化结果的解决方案。
This produces results like 2:41 (for 2 minutes and 41 seconds) and 08 (for 8 seconds). I would, however, like to keep at least one digit in the Minutes place, returning 0:08 instead of 08. Is this possible with the DateComponentsFormatter? I would prefer a solution that returns a localized result.
推荐答案
是。设置日期组件格式化程序允许的单位时,可以很容易地实现基于时间间隔的三元条件添加。
Yes. This can be easily accomplished adding a ternary conditional based on the time interval when setting the date components formatter allowed units:
Xcode 11•Swift 5.1
extension Formatter {
static let positional: DateComponentsFormatter = {
let positional = DateComponentsFormatter()
positional.unitsStyle = .positional
positional.zeroFormattingBehavior = .pad
return positional
}()
}
extension TimeInterval {
var positionalTime: String {
Formatter.positional.allowedUnits = self >= 3600 ?
[.hour, .minute, .second] :
[.minute, .second]
let string = Formatter.positional.string(from: self)!
return string.hasPrefix("0") && string.count > 4 ?
.init(string.dropFirst()) : string
}
}
用法
Usage
8.0.positionalTime // "0:08"
161.0.positionalTime // "2:41"
3600.0.positionalTime // "1:00:00"
这篇关于Swift DateComponentsFormatter删除前导零,但在Minutes位置至少保留一位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!