Skip to content

Add comparator between two dates ignoring time #313

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Foundation/NSDate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,23 @@ extension NSDate {
public func isEqualToDate(_ otherDate: NSDate) -> Bool {
return timeIntervalSinceReferenceDate == otherDate.timeIntervalSinceReferenceDate
}

public func isEqualToDateIgnoringTime(_ otherDate: NSDate) -> Bool {
let yearDayMonthComponents: NSCalendarUnit = [.Year, .Day, .Month]
let currentCalendar = NSCalendar.currentCalendar() // change to autoupdatingCurrentCalendar when it's implemented

let componentsFromSelf = currentCalendar.components( yearDayMonthComponents, fromDate: self);
let componentsFromOtherDate = currentCalendar.components( yearDayMonthComponents, fromDate: otherDate);

guard let unwrappedComponentsFromSelf = componentsFromSelf,
let unwrappedComponentsFromOtherDate = componentsFromOtherDate else {
return false
}

return ((unwrappedComponentsFromSelf.year == unwrappedComponentsFromOtherDate.year) &&
(unwrappedComponentsFromSelf.month == unwrappedComponentsFromOtherDate.month) &&
(unwrappedComponentsFromSelf.day == unwrappedComponentsFromOtherDate.day));
}
}

extension NSDate {
Expand Down
10 changes: 10 additions & 0 deletions TestFoundation/TestNSDate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ class TestNSDate : XCTestCase {
("test_LaterDate", test_LaterDate),
("test_Compare", test_Compare),
("test_IsEqualToDate", test_IsEqualToDate),
("test_IsEqualToDateIgnoringTime", test_IsEqualToDateIgnoringTime),

]
}

Expand Down Expand Up @@ -114,4 +116,12 @@ class TestNSDate : XCTestCase {
let d3 = d1.dateByAddingTimeInterval(ti)
XCTAssertTrue(d2.isEqualToDate(d3))
}

func test_IsEqualToDateIgnoringTime() {
let ti: NSTimeInterval = 1
let d1 = NSDate()
let d2 = d1.dateByAddingTimeInterval(ti)
let d3 = d2.dateByAddingTimeInterval(ti)
XCTAssertTrue(d2.isEqualToDateIgnoringTime(d3))
}
}