Dates ยท SWIFT RECIPE

Format a date

Use an explicit locale and time zone for a fixed format.

main.swift
import Foundation
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
print(formatter.string(from: Date(timeIntervalSince1970: 0)))

How it works

Set the locale and time zone for deterministic machine-readable output. For user interfaces, use dateStyle and timeStyle so presentation follows user preferences.

EXPECTED OUTPUT
1970-01-01 00:00:00

Keep in mind

yyyy is the calendar year. YYYY is the week-based year and can differ near New Year.

Read the Swift language reference