← Back to Swift Course | Chapter 14: Standard Library & Best Practices | Lesson 2 of 7

Date Basics

A Date is a precise point in time, and Swift gives you tools to compare, calculate, and print those moments.
Syntax
swift
import Foundation

let now = Date()
let later = now.addingTimeInterval(seconds)
let isEarlier = now < later
let seconds = later.timeIntervalSince(now)

Creating and Comparing Dates

Date() gives the current moment, and dates can be compared just like numbers to see which came first.

Example: Creating and Comparing Dates

markup
// Import the `Foundation` module
import Foundation
// Declare a constant `now`, set to `Date()`
let now = Date()
// Declare a constant `later`, set to `now.addingTimeInterval(60)`
let later = now.addingTimeInterval(60)
// Print `now < later` to the console
print(now < later)

Measuring the Interval Between Dates

.timeIntervalSince(_:) calculates the number of seconds separating two dates, useful for measuring durations.

Example: Measuring the Interval Between Dates

markup
// Import the `Foundation` module
import Foundation
// Declare a constant `start`, set to `Date()`
let start = Date()
// Declare a constant `end`, set to `start.addingTimeInterval(3600)`
let end = start.addingTimeInterval(3600)
// Declare a constant `interval`, set to `end.timeIntervalSince(start)`
let interval = end.timeIntervalSince(start)
// Print "Interval in seconds: \(interval)" to the console
print("Interval in seconds: \(interval)")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting Date from Foundation needs import Foundation at the top of the file before it can be used.
  2. Printing a raw Date directly and expecting locale-friendly formatting; use a DateFormatter for readable output.
  3. Assuming Date() returns a fixed value; each call captures the current moment, so results differ across calls and machines.
Chapter Summary
  • Date() from Foundation captures the current point in time.
  • Two dates can be compared directly with <, >, and ==.
  • .timeIntervalSince(_:) calculates the number of seconds between two dates.
  • DateFormatter (or newer Date.FormatStyle) converts a Date into human-readable text.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.