From 27eb16d75ac64463be6b691ce822ac435732e975 Mon Sep 17 00:00:00 2001 From: Jim Wang Date: Thu, 21 Mar 2024 04:49:50 +0800 Subject: [PATCH] Feat/nanosecond precision (#122) * feat: added support for adjusting time with nanosecond precision. * feat: change `endOfDay` to 23:59:59:999 --- Sources/DateHelper/DateHelper.swift | 5 +++-- Tests/DateHelperTests/DateAdjustingTests.swift | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Sources/DateHelper/DateHelper.swift b/Sources/DateHelper/DateHelper.swift index 944ecac..fe142d7 100644 --- a/Sources/DateHelper/DateHelper.swift +++ b/Sources/DateHelper/DateHelper.swift @@ -302,13 +302,14 @@ public extension Date { } /// Sets a new value to the specified component and returns as a new date - func adjust(hour: Int? = nil, minute: Int? = nil, second: Int? = nil, day: Int? = nil, month: Int? = nil) -> Date? { + func adjust(hour: Int? = nil, minute: Int? = nil, second: Int? = nil, nanosecond: Int? = nil, day: Int? = nil, month: Int? = nil) -> Date? { var comp = Date.components(self) comp.month = month ?? comp.month comp.day = day ?? comp.day comp.hour = hour ?? comp.hour comp.minute = minute ?? comp.minute comp.second = second ?? comp.second + comp.nanosecond = nanosecond ?? comp.nanosecond return Calendar.current.date(from: comp) } @@ -320,7 +321,7 @@ public extension Date { case .startOfDay: return adjust(hour: 0, minute: 0, second: 0) case .endOfDay: - return adjust(hour: 23, minute: 59, second: 59) + return adjust(hour: 23, minute: 59, second: 59, nanosecond: 999_000_000) // 23:59:59:999 case .startOfWeek: return calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear, .hour, .minute, .second, .nanosecond], from: self)) case .endOfWeek: diff --git a/Tests/DateHelperTests/DateAdjustingTests.swift b/Tests/DateHelperTests/DateAdjustingTests.swift index 41fa288..00b4ba0 100644 --- a/Tests/DateHelperTests/DateAdjustingTests.swift +++ b/Tests/DateHelperTests/DateAdjustingTests.swift @@ -105,7 +105,7 @@ final class DateHelperAdjustingTests: XCTestCase { func testDateAdjustEndOfDay() throws { guard let original = Calendar.current.date(from: DateComponents(year: 2009, month: 12, day: 06, hour: 18, minute: 14, second: 41)), let adjusted = original.adjust(for: .endOfDay), - let comparison = Calendar.current.date(from: DateComponents(year: 2009, month: 12, day: 06, hour: 23, minute: 59, second: 59)) else { + let comparison = Calendar.current.date(from: DateComponents(year: 2009, month: 12, day: 06, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000)) else { return } XCTAssertEqual(adjusted, comparison)