Issue #340
Use DateComponentsFormatter
https://nshipster.com/formatter/#datecomponentsformatter
Results in no padding 0
func format(second: TimeInterval) -> String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.hour, .minute]
formatter.zeroFormattingBehavior = .pad
return formatter.string(from: second)
}
XCTAssertEqual(format(second: 5400 ), "1:30")
XCTAssertEqual(format(second: 7200), "2:00")
XCTAssertEqual(format(second: 39600 ), "11:00")
Use mod
func format(minute: Int) -> String {
let h = minute / 60
let m = minute % 60
return "\(h.padZero()):\(m.padZero())"
}
private extension Int {
func padZero() -> String {
return String(format: "%02d", self)
}
}
XCTAssertEqual(format(minute: 90 ), "01:30")
XCTAssertEqual(format(minute: 120), "02:00")
XCTAssertEqual(format(minute: 660 ), "11:00")