Skip to content

Commit e13f3ad

Browse files
authored
Merge pull request #2890 from spevans/pr_date_distanceto_advancedby_5.3
[5.3] Date: Add distance(to:) and advanced(by:) introduced in macOS 10.15
2 parents f069950 + bf74f71 commit e13f3ad

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

Sources/Foundation/Date.swift

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,22 @@ public struct Date : ReferenceConvertible, Comparable, Equatable {
190190
public static func -=(lhs: inout Date, rhs: TimeInterval) {
191191
lhs = lhs - rhs
192192
}
193-
193+
194+
public typealias Stride = TimeInterval
195+
196+
/// Returns the `TimeInterval` between this `Date` and another given date.
197+
///
198+
/// - returns: The interval between the receiver and the another parameter. If the receiver is earlier than `other`, the return value is negative.
199+
public func distance(to other: Date) -> TimeInterval {
200+
return other.timeIntervalSince(self)
201+
}
202+
203+
/// Creates a new date value by adding a `TimeInterval` to this `Date`.
204+
///
205+
/// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more.
206+
public func advanced(by n: TimeInterval) -> Date {
207+
return self.addingTimeInterval(n)
208+
}
194209
}
195210

196211
extension Date : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable {

Tests/Foundation/Tests/TestDate.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ class TestDate : XCTestCase {
3434
("test_timeIntervalSinceReferenceDate", test_timeIntervalSinceReferenceDate),
3535
("test_recreateDateComponentsFromDate", test_recreateDateComponentsFromDate),
3636
("test_Hashing", test_Hashing),
37+
("test_advancedBy", test_advancedBy),
38+
("test_distanceTo", test_distanceTo),
3739
]
3840
}
3941

@@ -172,4 +174,22 @@ class TestDate : XCTestCase {
172174
]
173175
checkHashable(values, equalityOracle: { $0 == $1 })
174176
}
177+
178+
func test_advancedBy() {
179+
let date1 = dateWithString("2010-05-17 14:49:47 -0000")
180+
let date2 = dateWithString("2010-05-18 14:49:47 -0000")
181+
182+
XCTAssertEqual(date1.advanced(by: 86400), date2)
183+
XCTAssertEqual(date2.advanced(by: -86400), date1)
184+
XCTAssertEqual(date1.advanced(by: 0), date1)
185+
}
186+
187+
func test_distanceTo() {
188+
let date1 = dateWithString("2010-05-17 14:49:47 -0000")
189+
let date2 = dateWithString("2010-05-18 14:49:47 -0000")
190+
191+
XCTAssertEqual(date1.distance(to: date2), 86400)
192+
XCTAssertEqual(date2.distance(to: date1), -86400)
193+
XCTAssertEqual(date1.distance(to: date1), 0)
194+
}
175195
}

0 commit comments

Comments
 (0)