What am I doing wrong with NSDateComponentsFormatter?

对着背影说爱祢 提交于 2019-12-02 07:24:15

Swift 3.1 • Xcode 8.3.2

extension Formatter {
    static let dateComponents: DateComponentsFormatter = {
        let formatter = DateComponentsFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.unitsStyle = .full
        formatter.includesApproximationPhrase = true
        formatter.includesTimeRemainingPhrase = true
        formatter.maximumUnitCount = 2
        formatter.zeroFormattingBehavior = .default
        formatter.allowsFractionalUnits = false
        formatter.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute, .second]
        return formatter
    }()
}
extension TimeInterval {
    var remainingTime: String {
        return Formatter.dateComponents.string(from: self) ?? ""
    }
}

let interval = 60.0 * 60 * 24 * 7

let intervalstring = interval.remainingTime   //  "About 1 week remaining"

Positional Time

extension Formatter {
    static let positional: DateComponentsFormatter = {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .positional
        formatter.zeroFormattingBehavior = .default
        formatter.allowedUnits = [.hour, .minute, .second]
        return formatter
    }()

}
extension TimeInterval {
    var hourMinuteSecond: String {
        return Formatter.positional.string(from: self) ?? ""
    }
}

let time = 345.7

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