Date Basics
A Date is a precise point in time, and Swift gives you tools to compare, calculate, and print those moments.
Syntax
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
// 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)
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 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)")
Login to try C/C++/Java/PHP code in the editor
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
- 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: