Format a Date in Swift
Turn a Date into a localized string with the modern formatted API or a reusable DateFormatter.
Also known as: Swift date formatting, DateFormatter Swift
beginner
On recent OS versions, date.formatted(...) gives locale-aware output in one line. For custom or fixed patterns, configure a DateFormatter once and reuse it.
What it is
Swift offers two routes. The modern FormatStyle API — date.formatted(date: .abbreviated, time: .shortened) — is concise and automatically respects the user's locale and time zone. For a fixed machine-readable format such as an API timestamp, use a DateFormatter with an explicit dateFormat and pin its locale to en_US_POSIX so device settings can't change the output.
Creating a DateFormatter is relatively expensive, so build it once and reuse it rather than allocating one per row in a list.
Worked example
import Foundation
let now = Date()
// Modern, locale-aware display string
let display = now.formatted(date: .abbreviated, time: .shortened)
print(display) // e.g. "Jul 2, 2026 at 3:14 PM"
// Fixed machine format for APIs
let iso = DateFormatter()
iso.locale = Locale(identifier: "en_US_POSIX")
iso.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
print(iso.string(from: now)) // 2026-07-02T15:14:00+0000
Failure mode — when it misleads
Using a fixed dateFormat without setting locale to en_US_POSIX can silently break on devices set to non-Gregorian calendars or 12/24-hour overrides. For pure ISO 8601 timestamps prefer ISO8601DateFormatter, which is purpose-built and avoids format-string mistakes.
Related entries
Sources & further reading
- DateFormatter (article)