Swift 3 - Comparing Date objects
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Swift 3+, Date conforms to Comparable, so you can compare dates directly with <, >, ==, <=, and >=. Earlier Swift versions required using NSDate and compare(_:) with ComparisonResult. The Comparable conformance makes date comparisons straightforward and readable, and it works with all standard library functions that expect Comparable types (sorting, min/max, ranges).
Basic Comparison Operators
Creating Specific Dates for Comparison
Using compare(_:) (NSDate Style)
The compare(_:) method returns a ComparisonResult enum and is available for compatibility with code migrated from Objective-C.
Prefer <, >, == over compare(_:) in Swift code — they are more readable.
Comparing Only Date Components (Ignoring Time)
Two Date objects with the same calendar date but different times are not equal. To compare only the date portion, use Calendar:
Granularity Options
Time Interval Between Dates
Checking If a Date Falls Within a Range
Sorting Arrays of Objects by Date
Common Pitfalls
- Comparing dates with different time zones:
Datein Swift is an absolute point in time (seconds since reference date). TwoDateobjects representing the same moment are always equal regardless of how they were created. Time zone only matters when displaying or parsing dates, not when comparing. - Using
==when you mean "same day":date1 == date2compares to the sub-second level. Two dates on the same calendar day but different times are not equal. UseCalendar.isDate(_:inSameDayAs:)orcompare(_:to:toGranularity:)for date-only comparison. - Floating-point precision with
timeIntervalSince:Datestores time as aDouble(seconds). Two dates created independently for the "same" time may differ by tiny fractions. Avoid==for dates computed from intervals; compare with a tolerance or use granularity-based comparison. - Ignoring
Calendarlocale differences:Calendar.currentrespects the user's locale, which affects week boundaries and day transitions. A date that is "today" in one timezone may be "tomorrow" in another. Use a fixed calendar for server-side logic. - Using
NSDatecomparison in Swift 3+:NSDate.compare(_:)works but is verbose. Swift'sDatetype (value type, not reference) supports<,>,==directly. Prefer the native operators for clarity.
Summary
Dateconforms toComparablein Swift 3+ — use<,>,==directly- Use
Calendar.compare(_:to:toGranularity:)to compare at a specific precision (year, month, day, hour) - Use
Calendar.isDate(_:inSameDayAs:)to check if two dates fall on the same calendar day timeIntervalSince(_:)gives the difference in seconds as aDouble- Date ranges (
start...end) supportcontains(_:)for range checks - Sorting by date works with
sorted { $0.date < $1.date }sinceDateisComparable
Related reading
- Swift 3 - device tokens are now being parsed as '32BYTES
- Swift 3 Decimal, NSDecimal and NSDecimalNumber
- Swift 3 for loop with increment
- Swift 3 URLSession.shared Ambiguous reference to member 'dataTaskwithcompletionHandler error bug
- Swift add icon/image in UITextField
- Swift add icon/image in UITextField
- Swift addsubview and remove it
- Swift Alamofire How to get the HTTP response status code
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.