From e148ff60592e519b1a067d2cbfd0161922af1709 Mon Sep 17 00:00:00 2001 From: Jason R Tibbetts Date: Sat, 31 Jul 2021 11:54:52 -0400 Subject: [PATCH] No ticket: [refactor] Combined Cloisimis's TimeInterval.durationString extension with the TimeIntervalExtensions. --- Source/Util/TimeIntervalExtensions.swift | 12 ++++++++++++ Tests/Util/TimeIntervalExtensionsTests.swift | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/Source/Util/TimeIntervalExtensions.swift b/Source/Util/TimeIntervalExtensions.swift index cb57b6f..0f85787 100644 --- a/Source/Util/TimeIntervalExtensions.swift +++ b/Source/Util/TimeIntervalExtensions.swift @@ -12,4 +12,16 @@ public extension TimeInterval { var weeks: TimeInterval { return 7.0 * days } var years: TimeInterval { return 365.0 * days } + var formattedString: String? { + return Self.durationFormatter.string(from: self) + } + + static var durationFormatter: DateComponentsFormatter = { + let formatter = DateComponentsFormatter() + formatter.allowedUnits = [.hour, .minute, .second] + formatter.collapsesLargestUnit = true + + return formatter + }() + } diff --git a/Tests/Util/TimeIntervalExtensionsTests.swift b/Tests/Util/TimeIntervalExtensionsTests.swift index c62034c..ace8812 100644 --- a/Tests/Util/TimeIntervalExtensionsTests.swift +++ b/Tests/Util/TimeIntervalExtensionsTests.swift @@ -13,4 +13,24 @@ class TimeIntervalExtensionsTests: XCTestCase { XCTAssertEqual(2.years, 104.weeks + 2.days) } + // MARK: - durationString + + func testFormattedStringDropsHours() { + let timeInterval = 165.0000 // 2:45 + let durationString = timeInterval.formattedString + XCTAssertEqual(durationString, "2:45") + } + + func testFormattedStringIncludesHours() { + let timeInterval = (3.0 * 60.0 * 60.0) + 165.0000 // 3:02:45 + let durationString = timeInterval.formattedString + XCTAssertEqual(durationString, "3:02:45") + } + + func testFormattedStringHandlesNegativeValues() { + let timeInterval = -165.0000 // -2:45 + let durationString = timeInterval.formattedString + XCTAssertEqual(durationString, "-2:45") + } + }