Swift 3
Date Comparison
Date Objects
Programming
iOS Development

Swift 3 - Comparing Date objects

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

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

swift
1import Foundation
2
3let now = Date()
4let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: now)!
5let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: now)!
6
7// Direct comparison — Date conforms to Comparable
8print(now < tomorrow)      // true
9print(now > yesterday)     // true
10print(now == now)          // true
11print(yesterday >= tomorrow) // false
12
13// Min and max work automatically
14let dates = [tomorrow, yesterday, now]
15print(dates.min()!)  // yesterday
16print(dates.max()!)  // tomorrow
17print(dates.sorted()) // [yesterday, now, tomorrow]

Creating Specific Dates for Comparison

swift
1import Foundation
2
3var components = DateComponents()
4components.year = 2025
5components.month = 3
6components.day = 15
7components.hour = 10
8components.minute = 30
9
10let calendar = Calendar.current
11let march15 = calendar.date(from: components)!
12
13components.month = 6
14components.day = 1
15let june1 = calendar.date(from: components)!
16
17print(march15 < june1)  // true
18print(march15 == june1) // false

Using compare(_:) (NSDate Style)

The compare(_:) method returns a ComparisonResult enum and is available for compatibility with code migrated from Objective-C.

swift
1let date1 = Date()
2let date2 = Date().addingTimeInterval(3600)  // 1 hour later
3
4switch date1.compare(date2) {
5case .orderedAscending:
6    print("date1 is earlier")
7case .orderedDescending:
8    print("date1 is later")
9case .orderedSame:
10    print("dates are equal")
11}
12// Output: date1 is earlier

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:

swift
1import Foundation
2
3let calendar = Calendar.current
4
5// Same day, different times
6let morning = calendar.date(bySettingHour: 8, minute: 0, second: 0, of: Date())!
7let evening = calendar.date(bySettingHour: 20, minute: 0, second: 0, of: Date())!
8
9print(morning == evening)  // false — different times
10
11// Compare date components only
12let sameDay = calendar.isDate(morning, inSameDayAs: evening)
13print(sameDay)  // true
14
15// Compare specific components
16let result = calendar.compare(morning, to: evening, toGranularity: .day)
17print(result == .orderedSame)  // true
18
19let result2 = calendar.compare(morning, to: evening, toGranularity: .hour)
20print(result2 == .orderedSame)  // false — different hours

Granularity Options

swift
1// Compare at different levels of precision
2let date1 = /* March 15, 2025 10:30:45 */
3let date2 = /* March 15, 2025 14:20:10 */
4
5calendar.compare(date1, to: date2, toGranularity: .year)    // .orderedSame
6calendar.compare(date1, to: date2, toGranularity: .month)   // .orderedSame
7calendar.compare(date1, to: date2, toGranularity: .day)     // .orderedSame
8calendar.compare(date1, to: date2, toGranularity: .hour)    // .orderedAscending
9calendar.compare(date1, to: date2, toGranularity: .minute)  // .orderedAscending

Time Interval Between Dates

swift
1let start = Date()
2let end = start.addingTimeInterval(7200)  // 2 hours later
3
4// Seconds between dates
5let interval = end.timeIntervalSince(start)
6print(interval)  // 7200.0
7
8// Using DateComponents for human-readable difference
9let diff = Calendar.current.dateComponents([.hour, .minute], from: start, to: end)
10print("\(diff.hour!) hours, \(diff.minute!) minutes")  // 2 hours, 0 minutes

Checking If a Date Falls Within a Range

swift
1import Foundation
2
3let now = Date()
4let start = Calendar.current.date(byAdding: .hour, value: -1, to: now)!
5let end = Calendar.current.date(byAdding: .hour, value: 1, to: now)!
6
7// Using ClosedRange (Swift 3+)
8let range = start...end
9print(range.contains(now))  // true
10
11// Check if a date is in the past or future
12print(now > start)  // true — start is in the past
13if now < end {
14    print("end is still in the future")
15}
16
17// Check if a date is today
18let isToday = Calendar.current.isDateInToday(now)
19print(isToday)  // true
20
21// Other Calendar convenience methods
22Calendar.current.isDateInYesterday(start)
23Calendar.current.isDateInTomorrow(end)
24Calendar.current.isDateInWeekend(now)

Sorting Arrays of Objects by Date

swift
1struct Event {
2    let name: String
3    let date: Date
4}
5
6let events = [
7    Event(name: "Conference", date: Date().addingTimeInterval(86400)),
8    Event(name: "Meeting", date: Date()),
9    Event(name: "Deadline", date: Date().addingTimeInterval(-86400))
10]
11
12// Sort ascending (earliest first)
13let sorted = events.sorted { $0.date < $1.date }
14sorted.forEach { print($0.name) }
15// Deadline, Meeting, Conference
16
17// Sort descending (latest first)
18let reversed = events.sorted { $0.date > $1.date }

Common Pitfalls

  • Comparing dates with different time zones: Date in Swift is an absolute point in time (seconds since reference date). Two Date objects 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 == date2 compares to the sub-second level. Two dates on the same calendar day but different times are not equal. Use Calendar.isDate(_:inSameDayAs:) or compare(_:to:toGranularity:) for date-only comparison.
  • Floating-point precision with timeIntervalSince: Date stores time as a Double (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 Calendar locale differences: Calendar.current respects 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 NSDate comparison in Swift 3+: NSDate.compare(_:) works but is verbose. Swift's Date type (value type, not reference) supports <, >, == directly. Prefer the native operators for clarity.

Summary

  • Date conforms to Comparable in 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 a Double
  • Date ranges (start...end) support contains(_:) for range checks
  • Sorting by date works with sorted { $0.date < $1.date } since Date is Comparable

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.