Swift DateComponentsFormatter drop leading zeroes but keep at least one digit in Minutes place

℡╲_俬逩灬. 提交于 2019-12-11 04:47:52

问题


I am using the following DateComponentsFormatter in Swift:

let formatter = DateComponentsFormatter()
formatter.unitsStyle   = .positional
formatter.allowedUnits = [.hour, .minute, .second]
formatter.zeroFormattingBehavior = [.default]

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.


回答1:


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"



回答2:


Check out a different zeroFormattingBehavior property value. I use this to get the result I think you're seeking, but experiment as necessary...

    formatter.zeroFormattingBehavior = [.pad]


来源:https://stackoverflow.com/questions/54641424/swift-datecomponentsformatter-drop-leading-zeroes-but-keep-at-least-one-digit-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!