Last active
July 10, 2017 09:21
-
-
Save klaaspieter/49dfa3426a5d55aaf8d792076abd2ece to your computer and use it in GitHub Desktop.
Calendar extension to determine wether a date is after today
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension Calendar { | |
/// Returns `true` if the given date is after today, as defined by the calendar and calendar's locale. | |
/// | |
/// Because it's impossible to define the end of a day (there are an infinite number of | |
/// milliseconds between 23:59:59 and 00:00:00), this method instead ensures that | |
/// `date` >= `startOfTomorrow`. | |
/// | |
/// - parameter date: The specified date. | |
/// - returns: `true` if the given date is after today | |
func isDateAfterToday(_ date: Date) -> Bool { | |
let startOfToday = startOfDay(for: Date()) | |
guard let startOfTomorrow = self.date( | |
byAdding: .day, | |
value: 1, | |
to: startOfToday | |
) else { | |
return false | |
} | |
switch compare(date, to: startOfTomorrow, toGranularity: .day) { | |
case .orderedSame, .orderedAscending: | |
return false | |
case .orderedDescending: | |
return true | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import XCTest | |
class CalendarTest: XCTestCase { | |
func testIsAfterToday() { | |
let calendar = Calendar(identifier: .gregorian) | |
XCTAssertTrue(calendar.isDateAfterToday(.distantFuture)) | |
} | |
func testIsBeforeToday() { | |
let calendar = Calendar(identifier: .gregorian) | |
XCTAssertFalse(calendar.isDateAfterToday(.distantPast)) | |
} | |
func testIsToday() { | |
let calendar = Calendar(identifier: .gregorian) | |
XCTAssertFalse(calendar.isDateAfterToday(Date())) | |
} | |
func testWithStartOfTomorrow() { | |
let calendar = Calendar(identifier: .gregorian) | |
let startOfToday = calendar.startOfDay(for: Date()) | |
let startOfTomorrow = calendar.date(byAdding: .day, value: 1, to: startOfToday)! | |
XCTAssertTrue(calendar.isDateAfterToday(startOfTomorrow)) | |
} | |
func testWithApproximateEndOfToday() { | |
let calendar = Calendar(identifier: .gregorian) | |
let approximateEndOfToday = calendar.date( | |
bySettingHour: 23, | |
minute: 59, | |
second: 59, | |
of: Date() | |
)! | |
XCTAssertFalse(calendar.isDateAfterToday(approximateEndOfToday)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment