Swift
NSDate
DateComparison
iOSDevelopment
SwiftProgramming

NSDate Comparison using Swift

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Comparing dates in Swift is straightforward once you separate two related ideas: comparing exact moments in time and comparing calendar values such as day, month, or week. That distinction matters because Date and NSDate represent an instant, while human-friendly concepts such as "same day" depend on calendar and time zone rules.

Modern Swift code usually works with Date, but NSDate still appears when bridging with older Objective-C APIs. The comparison techniques are almost the same because the types bridge through Foundation.

Direct Time Comparison

If you want to know which instant happened first, use comparison operators on Date or call compare on NSDate.

swift
1import Foundation
2
3let now = Date()
4let later = now.addingTimeInterval(3600)
5
6if now < later {
7    print("now is earlier")
8}
9
10let nsNow = now as NSDate
11let nsLater = later as NSDate
12
13if nsNow.compare(nsLater as Date) == .orderedAscending {
14    print("nsNow is earlier")
15}

This kind of comparison is precise and calendar-independent. It is the right choice for deadlines, expiry timestamps, and event ordering.

Comparing Calendar Components

Many application rules are not about exact timestamps. A reminder app may need to know whether two dates fall on the same day, or whether a task is due this week. For that, use Calendar rather than raw comparison operators.

swift
1import Foundation
2
3let calendar = Calendar.current
4let first = Date()
5let second = first.addingTimeInterval(60 * 30)
6
7if calendar.isDate(first, inSameDayAs: second) {
8    print("same calendar day")
9}

This is important because two timestamps can differ by hours yet still belong to the same day in the user's local time zone.

Comparing Only Selected Components

If you need a rule such as "compare year and month but ignore day," extract date components first:

swift
1import Foundation
2
3let calendar = Calendar.current
4let first = calendar.date(from: DateComponents(year: 2026, month: 3, day: 7))!
5let second = calendar.date(from: DateComponents(year: 2026, month: 3, day: 28))!
6
7let firstParts = calendar.dateComponents([.year, .month], from: first)
8let secondParts = calendar.dateComponents([.year, .month], from: second)
9
10if firstParts == secondParts {
11    print("same year and month")
12}

That approach is much clearer than manually dividing seconds or assuming months always contain the same number of days.

Working With NSDate

When older APIs return NSDate, you can either compare with compare or bridge to Date and stay in Swift-native code:

swift
1import Foundation
2
3let start: NSDate = NSDate()
4let end: NSDate = start.addingTimeInterval(24 * 60 * 60) as NSDate
5
6switch start.compare(end as Date) {
7case .orderedAscending:
8    print("start comes first")
9case .orderedDescending:
10    print("start comes after end")
11case .orderedSame:
12    print("same instant")
13}

Bridging to Date is usually the cleaner direction for new code because it keeps your APIs more Swifty and consistent.

Sorting Dates

Collections of dates can be sorted with normal closure syntax because Date conforms to Comparable:

swift
1import Foundation
2
3let dates = [
4    Date().addingTimeInterval(300),
5    Date(),
6    Date().addingTimeInterval(-300)
7]
8
9let sorted = dates.sorted()
10print(sorted)

This is often simpler than repeated pairwise comparisons when you need chronological ordering.

Common Pitfalls

The most common mistake is using raw Date comparison for calendar questions such as "is this today" or "same week." Exact timestamp comparison ignores calendar boundaries, locale, and daylight saving rules. Use Calendar for those checks.

Another pitfall is forgetting time zones when parsing strings into dates. Two strings that look like the same day can become different instants if one formatter uses UTC and another uses the device locale.

A third issue is keeping new Swift code on NSDate everywhere just because one older API returns it. Bridge once, then work with Date unless you truly need Objective-C-specific behavior.

Summary

  • Use Date comparison operators for exact instant ordering.
  • Use Calendar when the rule depends on day, week, month, or locale-aware boundaries.
  • Bridge NSDate to Date in modern Swift code whenever possible.
  • Compare date components directly when only part of the timestamp matters.
  • Most date bugs come from mixing exact-time logic with calendar logic.

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.