我对NSDateComponentsFormatter做错了什么?

时间:2015-08-31 00:57:58

标签: swift nsdatecomponentsformatter

我最近发现了新的iOS8类NSDateComponentsFormatter,它允许您格式化时间间隔而不是日期。凉。我编写代码的次数比我想的要多。所以我决定尝试在操场上使用它,但我无法让它工作。这是我的(Swift)代码:

var componentsFormatter = NSDateComponentsFormatter()
componentsFormatter.allowedUnits =
  .CalendarUnitHour |
  .CalendarUnitMinute |
  .CalendarUnitSecond

componentsFormatter.unitsStyle = .Positional

let interval: NSTimeInterval = 345.7

let intervalstring = componentsFormatter.stringFromTimeInterval(interval)

println("Interval as String = \(intervalstring)")

显示

  

Interval as String = nil

我尝试了各种各样的事情,但没有快乐。有没有人有一个使用这个新课程的工作实例,或者你能发现我缺少的东西吗?

(我也说Objective-C,所以如果你在Objective-C中有示例代码也可以。)

1 个答案:

答案 0 :(得分:4)

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"

定位时间

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"