Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 146 ยท Standard Library and Foundation

Dates and Times

Learn Swift dates - Date, Calendar, DateComponents, DateFormatter, formatted(), ISO 8601, TimeZone, and Duration with ContinuousClock, plus the classic bugs with time zones and daylight saving.

Dates look easy and are famously hard. "Add one month to January 31." "How many days until the 1st?" "Show this meeting time to someone in Tokyo." Behind every one of those questions are leap years, daylight saving time, time zones, and calendars that are not Gregorian at all. Swift's Foundation gives you a careful set of types that handle all of it, as long as you use the right type for each job.

This lesson sorts those types out. A Date is a single instant. A Calendar turns instants into human fields (year, month, day) and back. DateComponents holds those fields. Formatters turn dates into text and text into dates. Duration and ContinuousClock measure elapsed time. Throughout, the examples fix the time zone and the starting dates, so that the output you see is the output you get on any computer.

Programs that print the current time (Date.now) give different output every run. The examples here use fixed dates, or print only things that are always true, such as whether elapsed time is positive. Do the same in your tests.

Date is just a moment in time

A Date is a point on a global timeline, stored as the number of seconds since a reference moment (the start of 2001 in UTC). It has no time zone, no calendar, and no format. "March 14, 3 pm" is not a Date until you say whose March and whose 3 pm.

Because a Date is only a number, it can be compared and subtracted directly.

Swift Date is a number of seconds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get 3600.0, true, 1700000000.0 and 721696400.0. The last number is later measured from the reference date, the start of 2001 in UTC, which is 978,307,200 seconds after the Unix epoch used by timeIntervalSince1970. Date.now is the current instant; the comparison now > start is true on any computer whose clock is set after November 2023.

TimeInterval is just a typealias for Double seconds. Never do date arithmetic by adding 86400 for "one day": a day can have 23 or 25 hours when clocks change. Use a Calendar.

Calendar and DateComponents

A Calendar knows the rules of a calendar system and a time zone. Give it a Date and it returns components; give it components and it returns a Date. Always set the time zone explicitly when you want reproducible results; the default is the user's current time zone.

Swift Breaking a Date into components

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The instant is Tuesday, 14 November 2023 at 22:13 UTC, so you read 2023 11 14 and 22 13. weekday counts from Sunday = 1, so Tuesday is 3. It is not a weekend, it is day 318 of the year, and November has 30 days (range(of:in:for:) counts them). Building a date from components with date(from:) returns an optional because the components might not describe a real date (2023-02-30 does not exist); 29 February 2024 is the number of seconds 1709164800.0.

Adding and subtracting correctly

date(byAdding:value:to:) respects the calendar. Adding a month to 31 January gives the end of February, not an invalid date.

Swift Calendar arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Adding one month to 31 January prints 2025-2-28: the calendar clamps to the last valid day. Adding 30 days is different and gives 2025-3-2. One year after leap day 2024 is 2025-2-28. The span from 1 January to 25 December is 358 days. These results are why you should think in calendar units (.month, .day) rather than in seconds.

Turning dates into text

There are two systems, and you should know both: the older DateFormatter and the newer format styles used by formatted().

formatted(): the modern way

Date.formatted() uses a format style that follows the user's locale. The pieces of the style are type-safe, so you cannot misspell a pattern.

Swift formatted() with styles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The same instant appears as Nov 14, 2023 at 10:13 PM, 14. November 2023, the custom layout November 14, 2023 at 10:13, and the ISO 8601 form 2023-11-14T22:13:20Z. The ending Z means UTC. If you call date.formatted() with no arguments, you get the user's locale and time zone, which is perfect for showing dates to people and a poor choice for logs or files.

DateFormatter: patterns and parsing

DateFormatter uses pattern letters (yyyy, MM, dd, HH, mm) and works for parsing as well. It is a class and expensive to create, so make one and reuse it. For fixed machine formats always set locale to en_US_POSIX, otherwise the user's region settings can change the output.

Swift DateFormatter with a fixed pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The pattern prints 2023-11-14 22:13; Tokyo is nine hours ahead (no daylight saving there), so the same instant becomes 2023-11-15 07:13, and the last line spells it out as Wednesday, 15 November 2023. Pattern letters are case sensitive: MM is month but mm is minutes, and yyyy is the year but YYYY is the "week-based year", which gives wrong results around New Year. Parsing bad text returns nil, never a crash.

Parsing ISO 8601

For data exchanged between systems, use ISO 8601 and the dedicated style, which is stricter than a hand-written pattern.

Swift Parsing and formatting ISO 8601

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

try? turns a failed parse into nil. The valid string parses to a number of seconds, and the second print shows only the date part, 2025-06-01. The impossible date 2025-13-45 fails to parse, so the comparison is true.

Time zones

A TimeZone is an offset from UTC plus the rules for daylight saving. Create one by identifier ("America/New_York", "Europe/Berlin"), not by a fixed number of hours, unless you really mean a fixed offset.

Swift The same moment in three time zones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The UTC line shows hour 9 and minute 46, New York is four hours behind (-4.0h, daylight saving), Kolkata is +5.5h ahead. Berlin is 1 hour from UTC in January and 2 in July, so 1 2, and the last line is true. Two golden rules follow:

  1. Store and transmit UTC (a Date, or an ISO 8601 string). Convert to a local zone only when showing it to a person.
  2. Never hard-code offsets. The rules for daylight saving change; the time zone database knows them.

Measuring elapsed time: Duration and ContinuousClock

Dates are wall-clock time, which can jump when the user changes the clock or the system syncs. To measure how long something took, use a monotonic clock. Swift's ContinuousClock never goes backwards, and its Duration type represents a length of time with exact integer precision.

Swift Duration arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

90 s + 1.5 s is 91.5 seconds; components is a pair of whole seconds and attoseconds ((seconds: 91, attoseconds: 500000000000000000)). The comparison prints true, dividing by two gives 45.75 seconds, and formatted(.units(...)) prints 1 minute, 32 seconds (only minutes and seconds were allowed, so the half second is rounded).

Swift Timing code with ContinuousClock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both lines are true on every machine. In a real program, print elapsed or log it to see the cost. For benchmarks run the code several times and compare, because the first run includes warm-up work. Task.sleep(for:) takes a Duration and never blocks a thread, and a slept duration is never shorter than requested.

Common mistakes

  • Using 86400 for a day. Use calendar.date(byAdding: .day, ...).
  • Parsing with the user's locale. Set en_US_POSIX on any DateFormatter that reads machine formats.
  • YYYY instead of yyyy. Week-year only matches the calendar year most of the time.
  • Comparing local clock times across zones. Compare Date values.
  • Storing local times without a zone. "2025-03-30 02:30" does not exist in many European zones, and "2025-10-26 02:30" happens twice.
  • Creating a DateFormatter in a loop. Create it once and reuse it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a Date represent?

    Date is a point in time. A Calendar and TimeZone are needed to read it as year, month and day.
  2. 2. Why is date.addingTimeInterval(86400) a poor way to get 'tomorrow'?

    Daylight saving makes some days shorter or longer. Calendar arithmetic respects those rules.
  3. 3. Which time representation should you store in a database or send to a server?

    UTC is unambiguous. Convert to a local zone only when showing the time to a person.
  4. 4. Why set locale = Locale(identifier: "en_US_POSIX") on a DateFormatter that handles machine-readable dates?

    Without a fixed locale the user's settings (12 or 24 hour clock, other calendars) can change the output of your fixed pattern.
  5. 5. Which clock should you use to measure how long a piece of code takes?

    Wall-clock time can jump when the clock is adjusted. A monotonic clock only moves forward.

Summary

  • Date is one instant (seconds since a reference point); it has no time zone or format. TimeInterval is a Double number of seconds.
  • Calendar converts between a Date and DateComponents; set calendar.timeZone explicitly for repeatable results.
  • Use calendar.date(byAdding:value:to:) instead of adding seconds; adding a month to 31 January clamps to the end of February.
  • date.formatted(...) with Date.FormatStyle is locale-aware and type-safe; .iso8601 is the fixed machine format.
  • DateFormatter needs en_US_POSIX for fixed patterns; yyyy is the year, YYYY is the week-year, and MM is month while mm is minutes.
  • Store and transmit UTC; use TimeZone(identifier:) for display and never hard-code offsets.
  • Duration is exact integer-based time, and ContinuousClock.measure times code without being affected by clock changes.

Next: Number and Measurement Formatting shows how to display numbers, units and sizes for readers around the world.