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
import Foundation
let now = Date()
let later = now.addingTimeInterval(60)
print(now < later)
Login to try C/C++/Java/PHP code in the editor
Measuring the Interval Between Dates
.timeIntervalSince(_:) calculates the number of seconds separating two dates, useful for measuring durations.
Example: Measuring the Interval Between Dates
import Foundation
let start = Date()
let end = start.addingTimeInterval(3600)
let interval = end.timeIntervalSince(start)
print("Interval in seconds: \(interval)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting
Datefrom Foundation needsimport Foundationat the top of the file before it can be used. - Printing a raw
Datedirectly and expecting locale-friendly formatting; use aDateFormatterfor readable output. - 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 newerDate.FormatStyle) converts aDateinto human-readable text.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: