Dates ยท SWIFT RECIPE

Compare two dates

Compare moments in time, or compare just the calendar day.

main.swift
import Foundation
let earlier = Date(timeIntervalSince1970: 0)
let later = Date(timeIntervalSince1970: 86400)
print(earlier < later)
print(earlier == later)
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
print(calendar.isDate(earlier, inSameDayAs: later))

How it works

Date represents an instant. Use <, >, and == for instant comparisons. Use Calendar when comparing calendar days, because different instants can fall on the same day.

EXPECTED OUTPUT
true
false
false

Keep in mind

Choose the time zone deliberately. A local calendar day is not always 86,400 seconds.

Read the Swift language reference