Skip to content

Commit

Permalink
Feat/nanosecond precision (#122)
Browse files Browse the repository at this point in the history
* feat: added support for adjusting time with nanosecond precision.

* feat: change `endOfDay` to 23:59:59:999
  • Loading branch information
yyjim authored Mar 20, 2024
1 parent f75829d commit 27eb16d
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
5 changes: 3 additions & 2 deletions Sources/DateHelper/DateHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion Tests/DateHelperTests/DateAdjustingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 27eb16d

Please sign in to comment.