Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add isBetween method to date extension #248

Merged
merged 4 commits into from Sep 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Expand Up @@ -11,7 +11,8 @@ All notable changes to this project will be documented in this file.
> N/A
>
> ### Enhancements
> N/A
> - New **Date** extensions
> - added `isBetween(_ startDate: Date, _ endDate: Date, includeBounds: Bool = false) -> Bool` method to check if a date is between two other dates.
>
> ### Bugfixes
> N/A
Expand Down
16 changes: 15 additions & 1 deletion Sources/Extensions/Foundation/DateExtensions.swift
Expand Up @@ -709,7 +709,21 @@ public extension Date {
public func daysSince(_ date: Date) -> Double {
return self.timeIntervalSince(date)/(3600*24)
}


/// SwifterSwift: check if a date is between two other dates
///
/// - Parameter startDate: start date to compare self to.
/// - Parameter endDate: endDate date to compare self to.
/// - Parameter includeBounds: true if the start and end date should be included (default is false)
/// - Returns: true if the date is between the two given dates.
public func isBetween(_ startDate: Date, _ endDate: Date, includeBounds: Bool = false) -> Bool {
if includeBounds {
return startDate.compare(self).rawValue * self.compare(endDate).rawValue >= 0
} else {
return startDate.compare(self).rawValue * self.compare(endDate).rawValue > 0
}
}

}


Expand Down
25 changes: 25 additions & 0 deletions Tests/FoundationTests/DateExtensionsTests.swift
Expand Up @@ -683,4 +683,29 @@ class DateExtensionsTests: XCTestCase {
XCTAssertEqual(date, dateFromUnixTimestamp)
}

func testIfDateIsBetween() {
var date = Date(timeIntervalSince1970: 512) // 1970-01-01T00:08:32.000Z
let startDate = Date(timeIntervalSince1970: 511)
let endDate = Date(timeIntervalSince1970: 513)
XCTAssertTrue(date.isBetween(startDate, endDate))

date = Date(timeIntervalSince1970: 511)
XCTAssertTrue(date.isBetween(startDate, endDate, includeBounds: true))

date = Date(timeIntervalSince1970: 513)
XCTAssertTrue(date.isBetween(startDate, endDate, includeBounds: true))

date = Date(timeIntervalSince1970: 511)
XCTAssertFalse(date.isBetween(startDate, endDate))

date = Date(timeIntervalSince1970: 513)
XCTAssertFalse(date.isBetween(startDate, endDate))

date = Date(timeIntervalSince1970: 230)
XCTAssertFalse(date.isBetween(startDate, endDate))

date = Date(timeIntervalSince1970: 550)
XCTAssertFalse(date.isBetween(startDate, endDate))
}

}