-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimeElapsedFormat.swift
More file actions
53 lines (46 loc) · 1.69 KB
/
TimeElapsedFormat.swift
File metadata and controls
53 lines (46 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//
// TimeElapsedFormat.swift
//
// Copyright 2023 OpenAlloc LLC
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//
import Foundation
public enum TimeElapsedFormat {
case hh_mm
case hh_mm_ss
case mm_ss
}
/// Format elapsed seconds from 00:00:00 up to 23:59:59 (HH:MM:SS), or up to (but not including) what the format will accommodate.
public func formatElapsed(seconds: UInt, timeElapsedFormat: TimeElapsedFormat = .hh_mm_ss) -> String? {
let secondsPerHour: UInt = 3600
let secondsPerDay: UInt = 24 * secondsPerHour
let upperBound: UInt = switch timeElapsedFormat {
case .hh_mm:
secondsPerDay
case .hh_mm_ss:
secondsPerDay
case .mm_ss:
secondsPerHour
}
guard (0 ..< upperBound).contains(seconds) else { return nil }
let hours = seconds / 60 / 60
let mins = seconds / 60 % 60
let secs = seconds % 60
switch timeElapsedFormat {
case .hh_mm:
return String(format: "%02i:%02i", hours, mins)
case .hh_mm_ss:
return String(format: "%02i:%02i:%02i", hours, mins, secs)
case .mm_ss:
return String(format: "%02i:%02i", mins, secs)
}
}
/// Format elapsed TimeInterval from 00:00:00 up to 23:59:59 (HH:MM:SS), or up to (but not including) one day.
/// Fractions of a second are ignored.
public func formatElapsed(timeInterval: TimeInterval, timeElapsedFormat: TimeElapsedFormat = .hh_mm_ss) -> String? {
guard timeInterval >= 0 else { return nil }
return formatElapsed(seconds: UInt(timeInterval), timeElapsedFormat: timeElapsedFormat)
}