How to format hour minute from time interval in Swift

Issue #340

Use DateComponentsFormatter

https://nshipster.com/formatter/#datecomponentsformatter

Results in no padding 0

1
2
3
4
5
6
7
8
9
10
11
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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")

Comments