Swift
NSDate
TimeDifference
SwiftProgramming
iOSDevelopment

Find difference in seconds between NSDates as integer using Swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

If you need the difference in seconds between two dates in Swift, the simplest answer is to measure the elapsed time interval and then convert it to an integer if whole seconds are what you need. NSDate and Swift's Date both represent absolute points in time, so the operation is about elapsed seconds rather than calendar math. The main decisions are whether direction matters and how you want fractional seconds rounded.

Use timeIntervalSince(_:)

Foundation provides timeIntervalSince(_:), which returns a TimeInterval. In Swift, TimeInterval is a type alias for Double.

swift
1import Foundation
2
3let start = Date(timeIntervalSince1970: 1_700_000_000)
4let end = Date(timeIntervalSince1970: 1_700_000_125)
5
6let seconds = end.timeIntervalSince(start)
7print(seconds)      // 125.0
8print(Int(seconds)) // 125

This is the normal solution when the requirement is "how many seconds elapsed between these two instants."

The Same Idea Works with NSDate

Older code may still use NSDate. Swift bridges it cleanly to Date, so the calculation is effectively the same.

swift
1import Foundation
2
3let earlier: NSDate = NSDate(timeIntervalSince1970: 1_700_000_000)
4let later: NSDate = NSDate(timeIntervalSince1970: 1_700_000_125)
5
6let diff = later.timeIntervalSince(earlier as Date)
7let wholeSeconds = Int(diff)
8
9print(wholeSeconds)

In modern Swift, prefer Date for new code, but you do not need a different algorithm for NSDate.

Decide Whether You Need Truncation or Rounding

Converting a Double to Int truncates toward zero. That is sometimes correct and sometimes not.

swift
1import Foundation
2
3let start = Date()
4let end = start.addingTimeInterval(2.9)
5
6let exact = end.timeIntervalSince(start)
7
8print(Int(exact))                  // 2
9print(Int(exact.rounded()))        // 3
10print(Int(exact.rounded(.down)))   // 2

If you are implementing a countdown display, rounded values may feel more natural. If you are computing precise durations for logging or retry logic, truncation may be the safer rule. Choose intentionally.

Preserve the Sign When Direction Matters

The sign of the result tells you which date is later.

swift
1import Foundation
2
3let a = Date(timeIntervalSince1970: 200)
4let b = Date(timeIntervalSince1970: 180)
5
6print(a.timeIntervalSince(b)) // 20.0
7print(b.timeIntervalSince(a)) // -20.0

That is useful when your code needs to know whether a deadline has passed or whether an event occurred before another one.

If direction does not matter, wrap the interval with abs.

swift
let magnitude = abs(b.timeIntervalSince(a))
print(Int(magnitude)) // 20

Know When You Actually Need Calendar Logic

Elapsed seconds are not the same thing as calendar components. If the question is "how many seconds passed," timeIntervalSince(_:) is correct. If the question is "how many days by local calendar rules," use Calendar and DateComponents.

swift
1import Foundation
2
3let calendar = Calendar.current
4let now = Date()
5let tomorrow = calendar.date(byAdding: .day, value: 1, to: now)!
6
7let elapsedSeconds = tomorrow.timeIntervalSince(now)
8print(Int(elapsedSeconds))

This distinction matters around daylight saving transitions, month boundaries, and user-facing date displays. Stopwatch logic and calendar logic answer different questions.

Keep Precision Until the End

A useful habit is to keep the value as TimeInterval until the last possible moment. Once you convert to Int, the fractional detail is gone.

swift
1import Foundation
2
3func hasTimedOut(start: Date, timeout: TimeInterval) -> Bool {
4    return Date().timeIntervalSince(start) >= timeout
5}

That pattern avoids accidental precision loss in code that may later need milliseconds or tenths of a second.

Common Pitfalls

The most common mistake is assuming that Int(seconds) rounds. It does not; it truncates toward zero.

Another issue is using calendar APIs when the requirement is simply elapsed time. Calendar math is heavier and can change semantics around local time rules.

Developers also sometimes ignore the sign of the interval and then lose useful information about which date is earlier.

Finally, new Swift code should generally use Date rather than NSDate, even though the latter still works through bridging.

Summary

  • Use timeIntervalSince(_:) to compute elapsed seconds between two dates.
  • 'TimeInterval is a Double, so choose truncation or rounding deliberately.'
  • Keep the sign if direction matters; use abs if it does not.
  • Use Date for new Swift code, with NSDate bridging cleanly when needed.
  • Switch to calendar APIs only when the requirement is about calendar components, not raw elapsed time.

Course illustration
Course illustration

All Rights Reserved.