For a fixed pattern, use a DateFormatter with a dateFormat, the en_US_POSIX locale and a time zone: f.dateFormat = "yyyy-MM-dd HH:mm:ss", then f.string(from: date) gives 2026-07-04 18:30:05 and f.date(from: text) parses the other way, returning nil on a mismatch. Write yyyy, not YYYY. For ISO 8601 use ISO8601DateFormatter, and for text people read, use date.formatted(date: .long, time: .shortened).
A Swift Date is a single moment in time with no format, no time zone and no calendar attached. Turning it into text, or text into a Date, always goes through a formatter that supplies those three things. DateFormatter handles fixed patterns in both directions, ISO8601DateFormatter handles the timestamps APIs send, and formatted() with Date.FormatStyle builds text for people in their own locale. The sections below cover each one, the pattern letters that differ only by case, converting a date string into a different date string, and creating a Date from parts, then a table to pick from. All of them need import Foundation. Each example runs on this page: hit Run, then edit the code and run it again.
1DateFormatter with a fixed formatRecommended
Create a DateFormatter, set dateFormat to a pattern of letters, and call string(from:). For any fixed format, also set two properties. locale to en_US_POSIX, a locale that never changes, so the user's region, calendar and 12- or 24-hour setting can't rewrite your pattern (section 3 shows what goes wrong without it). And timeZone, because the formatter otherwise uses the device's zone. Creating a formatter costs far more than using one, so make it once and reuse it rather than building a new one for every date. Text inside single quotes, like 'at', is printed as is.
import Foundation // Make the formatter once and reuse it: creating one is costly let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(identifier: "UTC") // A fixed moment: 2026-07-04 18:30:05 UTC let date = Date(timeIntervalSince1970: 1_783_189_805) formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" print(formatter.string(from: date)) formatter.dateFormat = "EEEE, MMM d, yyyy 'at' h:mm a" print(formatter.string(from: date)) formatter.dateFormat = "dd/MM/yyyy" print(formatter.string(from: date)) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" print(formatter.string(from: date)) // The same moment, shown in another time zone formatter.timeZone = TimeZone(identifier: "America/New_York") formatter.dateFormat = "MMM d, h:mm a zzz" print(formatter.string(from: date)) // print(date) always shows UTC, whatever a formatter would say print(date)
Output
One Date, five strings: 2026-07-04 18:30:05, Saturday, Jul 4, 2026 at 6:30 PM (MMM is the short month name; MMMM spells it out), 04/07/2026 and the ISO form 2026-07-04T18:30:05Z, where ZZZZZ writes Z for UTC. Switching the time zone to New York changes the text, not the date: Jul 4, 2:30 PM EDT. A plain print(date) ignores all of this and shows 2026-07-04 18:30:05 +0000; it is for debugging, so don't parse it or show it to users. The examples use Date(timeIntervalSince1970:) so the output is the same on every run; use Date() for the current moment.
2Pattern letters: yyyy vs YYYY, MM vs mm, HH vs hh
The letters come from the Unicode date pattern standard, and case matters: MM is the month and mm the minute, HH is the hour from 0 to 23 and hh from 1 to 12, dd is the day of the month and DD the day of the year. The worst pair is yyyy and YYYY. YYYY is the year of the week: for the few days around New Year where a week spans two years, it gives the other year. The rest of the time the two agree, so the bug passes every test until late December.
import Foundation let f = DateFormatter() f.locale = Locale(identifier: "en_US_POSIX") f.timeZone = TimeZone(identifier: "UTC") let july = Date(timeIntervalSince1970: 1_783_189_805) // 2026-07-04 18:30:05 let patterns = [ "yyyy-MM-dd", "yyyy-mm-dd", "dd", "DD", "HH:mm", "hh:mm", "h:mm a", "MMM", "MMMM", "E", "EEEE", "yy", "SSS", "Z", "zzz", ] for pattern in patterns { f.dateFormat = pattern let label = pattern.padding(toLength: 12, withPad: " ", startingAt: 0) print(label, f.string(from: july)) } // yyyy is the calendar year, YYYY the year of the week let lateDecember = Date(timeIntervalSince1970: 1_798_416_000) // 2026-12-28 for day in [july, lateDecember] { f.dateFormat = "yyyy-MM-dd" let right = f.string(from: day) f.dateFormat = "YYYY-MM-dd" print("yyyy:", right, " YYYY:", f.string(from: day)) }
Output
yyyy-mm-dd prints 2026-30-04: the 30 is the minute. DD gives 185, the day of the year, and hh:mm gives 06:30 with no hint that it is evening, so pair h or hh with a (6:30 PM). The last two lines are the trap: on July 4 both year letters print 2026, but on December 28, 2026, YYYY prints 2027-12-28, a date a year in the future. Use YYYY only together with week numbers (ww). Other useful letters: SSS for milliseconds, Z for an offset like +0000, and zzz for a zone name.
3String to Date, and back in another format
To convert a date string into a different date string, parse it with one formatter and write it with another. date(from:) returns an optional Date?: nil when the text doesn't match the pattern or names a day that doesn't exist, so unwrap it with guard let or if let instead of !. Parsing is where en_US_POSIX matters most. Without it the formatter reads the numbers with the user's calendar, so the same pattern can produce a different date, or nil, on someone else's phone.
import Foundation func makeFormatter(_ format: String) -> DateFormatter { let f = DateFormatter() f.locale = Locale(identifier: "en_US_POSIX") f.timeZone = TimeZone(identifier: "UTC") f.dateFormat = format return f } let input = makeFormatter("yyyy-MM-dd HH:mm:ss") let output = makeFormatter("MMM d, yyyy 'at' h:mm a") // String -> Date -> String in another format; nil if it doesn't parse func reformat(_ text: String) -> String? { guard let date = input.date(from: text) else { return nil } return output.string(from: date) } let samples = [ "2026-07-04 18:30:05", "2026-07-04", "04/07/2026 18:30:05", "2026-02-30 10:00:00", ] for text in samples { print(text, "->", reformat(text) ?? "nil") } // A day-only string becomes midnight in the formatter's time zone if let christmas = makeFormatter("dd/MM/yyyy").date(from: "25/12/2026") { print(christmas) } // Why en_US_POSIX: the same pattern with a Thai locale let thai = DateFormatter() thai.locale = Locale(identifier: "th_TH") thai.timeZone = TimeZone(identifier: "UTC") thai.dateFormat = "yyyy-MM-dd HH:mm:ss" if let date = thai.date(from: "2026-07-04 18:30:05") { print("th_TH reads 2026 as", date) } if let date = input.date(from: "2026-07-04 18:30:05") { print("th_TH writes", thai.string(from: date)) }
Output
The full string converts to Jul 4, 2026 at 6:30 PM. A date without the time, a different order and February 30 all give nil: the pattern must match the whole shape of the text, and the formatter rejects days that don't exist. It is not strict about everything, though: here it also accepted spaces around the text and single digits such as 2026-7-4 8:3:5, so validate the shape yourself if that matters. The Thai lines show the locale problem. th_TH uses the Buddhist calendar, so it reads 2026 as a Buddhist year (1483-07-13 in the Gregorian calendar) and writes 2569-07-04. With en_US_POSIX the result no longer depends on the device.
4ISO 8601 with fractional seconds
Timestamps from JSON APIs usually look like 2026-07-04T18:30:05.123Z (ISO 8601, or RFC 3339). Rather than write that pattern by hand, use ISO8601DateFormatter: it always uses the Gregorian calendar, defaults to UTC and needs no locale. By default it reads and writes whole seconds; add .withFractionalSeconds to its formatOptions for milliseconds. Each setting accepts only its own shape, so when an API sends both, try one formatter and fall back to the other. Date.ISO8601FormatStyle is the newer value-type version of the same thing.
import Foundation // Whole seconds: 2026-07-04T18:30:05Z let iso = ISO8601DateFormatter() // With milliseconds: 2026-07-04T18:30:05.123Z let isoMillis = ISO8601DateFormatter() isoMillis.formatOptions = [.withInternetDateTime, .withFractionalSeconds] let stamp = "2026-07-04T18:30:05.123Z" if let date = isoMillis.date(from: stamp) { print(date.timeIntervalSince1970) print(isoMillis.string(from: date)) print(iso.string(from: date)) } // Each one accepts only its own shape print(iso.date(from: stamp) as Any) print(isoMillis.date(from: "2026-07-04T18:30:05Z") as Any) // Accept both: try one, then the other func parseISO(_ text: String) -> Date? { isoMillis.date(from: text) ?? iso.date(from: text) } let inputs = [ "2026-07-04T18:30:05Z", "2026-07-04T18:30:05.5Z", "2026-07-04T20:30:05+02:00", "2026-07-04 18:30:05", ] for text in inputs { let parsed = parseISO(text).map { iso.string(from: $0) } print(text, "->", parsed ?? "nil") } // Date.ISO8601FormatStyle: the same, as a format style let style = Date.ISO8601FormatStyle(includingFractionalSeconds: true) let date = try style.parse(stamp) print(date.formatted(style))
Output
The milliseconds survive the round trip (1783189805.123, 2026-07-04T18:30:05.123Z); the plain formatter drops them when it writes. The two nil lines are the usual cause of "my ISO date won't parse": the plain formatter rejects a fraction and the fractional one rejects a timestamp without one. parseISO takes both, any number of digits after the point, and an offset such as +02:00, which it converts to UTC. A space instead of the T is not ISO 8601 and gives nil; parse that with a DateFormatter as in section 3. try style.parse throws instead of returning nil, which is why that line needs try.
5formatted() and Date.FormatStyle for display
For text people read, don't pick a pattern at all: ask for a style and let the locale decide the order, the month names and the clock. date.formatted(date: .long, time: .shortened) takes preset styles, and .dateTime lets you list the fields you want, such as .dateTime.year().month().day(). With no locale they follow the user's device, which is what an app wants. Here the device locale is en_001 (international English), so the examples pass a locale and time zone when the output must be predictable. The same style parses too: Date(text, strategy: style) throws when the text doesn't fit.
import Foundation let date = Date(timeIntervalSince1970: 1_783_189_805) // 2026-07-04 18:30:05 let us = Locale(identifier: "en_US") let utc = TimeZone(identifier: "UTC")! // No locale: follows the device (en_001 here) print(date.formatted(date: .long, time: .shortened)) // Preset styles with a fixed locale and time zone let long = Date.FormatStyle(date: .long, time: .shortened, locale: us, timeZone: utc) print(date.formatted(long)) let numeric = Date.FormatStyle(date: .numeric, time: .omitted, locale: us, timeZone: utc) print(date.formatted(numeric)) // Pick the fields; each locale orders and spells them its own way let fields = Date.FormatStyle(locale: us, timeZone: utc) .year().month(.abbreviated).day().hour().minute() for id in ["en_US", "en_GB", "de_DE", "ja_JP"] { print(id, date.formatted(fields.locale(Locale(identifier: id)))) } // Parse with the same kind of style let parser = Date.FormatStyle( date: .abbreviated, time: .omitted, locale: us, timeZone: utc ) do { let parsed = try Date("Dec 25, 2026", strategy: parser) print(parsed) _ = try Date("hello", strategy: parser) } catch { print("could not parse") }
Output
Without a locale the long style prints 4 July 2026 at 6:30 PM; with en_US it is July 4, 2026 at 6:30 PM. The field style shows why you shouldn't hard-code a pattern for display: the same fields come out as Jul 4, 2026 at 6:30 PM, 4 Jul 2026 at 18:30, 4. Juli 2026, 18:30 and 2026年7月4日 18:30, each with the clock its locale expects. Parsing "Dec 25, 2026" works, and "hello" throws, so the last line is could not parse. One detail that breaks string comparisons: here the gap before PM in formatted() output is a narrow no-break space (U+202F), not a plain space, so don't test the result against a typed string. formatted() and Date.FormatStyle need iOS 15 or macOS 12 on Apple platforms; on older systems use DateFormatter with dateStyle and timeStyle.
6Creating a Date from a timestamp or components
Date() is the current moment. For a fixed one, start from a Unix timestamp in seconds with Date(timeIntervalSince1970:); a timestamp in milliseconds, as JavaScript and many APIs send, is divided by 1000 first. To build a date from a year, month and day, fill in DateComponents and ask a Calendar. The calendar's time zone decides which moment those numbers mean, so set it. dateComponents(_:from:) goes the other way and reads the parts back out.
import Foundation // From a Unix timestamp in seconds, or milliseconds / 1000 let fromSeconds = Date(timeIntervalSince1970: 1_783_189_805) let millis: Int64 = 1_783_189_805_123 let fromMillis = Date(timeIntervalSince1970: Double(millis) / 1000) print(fromSeconds) print(fromMillis.timeIntervalSince1970) // From year, month, day and time, with a Calendar var calendar = Calendar(identifier: .gregorian) calendar.timeZone = TimeZone(identifier: "UTC")! let parts = DateComponents(year: 2026, month: 7, day: 4, hour: 18, minute: 30) if let date = calendar.date(from: parts) { print(date) } // The same numbers in New York time are a different moment var newYork = calendar newYork.timeZone = TimeZone(identifier: "America/New_York")! if let date = newYork.date(from: parts) { print(date) } // Out-of-range parts roll over instead of returning nil let feb30 = DateComponents(year: 2026, month: 2, day: 30) if let date = calendar.date(from: feb30) { print(date) } print(DateComponents(calendar: calendar, year: 2026, month: 2, day: 30).isValidDate) // And back: read the parts of a date (weekday 1 is Sunday) let c = calendar.dateComponents([.year, .month, .day, .weekday], from: fromSeconds) print(c.year ?? 0, c.month ?? 0, c.day ?? 0, c.weekday ?? 0) // Date() is the current moment print(Date() > fromSeconds)
Output
Milliseconds stay as a fraction: 1783189805.123. The components give 2026-07-04 18:30:00 +0000 in UTC, and the same numbers read as New York time are 22:30 UTC, four hours later. February 30 doesn't fail: the calendar rolls it over to 2026-03-02, unlike DateFormatter in section 3, which returned nil. Check isValidDate (false here) when the parts come from a user. Reading the parts back gives 2026 7 4 7: weekday 7 is Saturday, because the Gregorian calendar counts from Sunday as 1.
7Which should you use?
| Method | Direction | Best for |
|---|---|---|
| DateFormatter + dateFormat | Date ⇄ String | Fixed formats: files, logs, APIs that are not ISO 8601. Set en_US_POSIX and a time zone |
| ISO8601DateFormatter | Date ⇄ String | ISO 8601 / RFC 3339 timestamps; add .withFractionalSeconds for milliseconds |
| date.formatted(…) | Date → String | Text people read, in their own locale |
| Date(text, strategy:) | String → Date | Parsing with a format style; throws instead of returning nil |
| Calendar.date(from: DateComponents) | Numbers → Date | Building a date from year, month, day; reading parts back |
| print(date) | Debug only | Logging; always UTC, never for users or parsing |
Frequently asked questions
Why does my date show next year at the end of December?
The pattern uses YYYY, the year of the week, instead of yyyy, the calendar year. They agree most of the year, but for December 28, 2026 YYYY-MM-dd prints 2027-12-28, because that week already counts as week 1 of 2027. Use yyyy unless you also print a week number with ww.
Why does DateFormatter.date(from:) return nil?
The text doesn't match the pattern exactly: a missing time part, a different separator, mm where you meant MM, a literal T written without quotes ('T'), or a day that doesn't exist such as February 30. A locale other than en_US_POSIX can also break it, because month names, AM/PM markers and the calendar change with the locale. Set locale to en_US_POSIX and timeZone explicitly, then check the pattern letter by letter.
Why does print(date) show a different time from my formatter?
print(date) always writes the moment in UTC, like 2026-07-04 18:30:05 +0000. A formatter writes it in its own timeZone, the device's zone unless you set one. Both describe the same instant; only the text differs. Don't parse the output of print(date) or show it to users.
How do I format a date with milliseconds in Swift?
Add SSS to the pattern: yyyy-MM-dd HH:mm:ss.SSS gives 2026-07-04 14:30:05.250 for a date 0.25 s past the second in New York time. For ISO 8601, use ISO8601DateFormatter with formatOptions = [.withInternetDateTime, .withFractionalSeconds], which writes 2026-07-04T18:30:05.123Z.
How do I decode ISO 8601 dates with fractional seconds in JSONDecoder?
Set decoder.dateDecodingStrategy = .custom { decoder in … }: read the value with try decoder.singleValueContainer().decode(String.self), return isoMillis.date(from: text) ?? iso.date(from: text) using the two formatters from section 4, and throw DecodingError.dataCorruptedError(in:debugDescription:) when both return nil. That accepts timestamps with and without milliseconds. The built-in .iso8601 strategy is fine when every timestamp has whole seconds.
Should I create a new DateFormatter every time?
No. Creating a DateFormatter costs much more than calling string(from:) on one, and code that makes one per table row or per JSON item is a classic slowdown. Keep one per format, for example a static let on a type or a global constant, and set its locale, timeZone and dateFormat once. A Date.FormatStyle is a struct you can store in a constant and reuse the same way.
How do I get the current date as a string?
Pass Date() to a formatter: formatter.string(from: Date()) for a fixed pattern, or Date().formatted(date: .abbreviated, time: .shortened) for display in the user's locale. The result changes on every run, which is why the examples on this page use fixed dates from Date(timeIntervalSince1970:).