← 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.

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 Foundation
let now = Date()
let later = now.addingTimeInterval(60)
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 Foundation
let start = Date()
let end = start.addingTimeInterval(3600)
let interval = end.timeIntervalSince(start)
print("Interval in seconds: \(interval)")
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.