This post presents a series of code snippets for parsing and formatting UTC and local Dates in Swift.
- UTC Date Format
- Local Timezone Date Format
- Date Formatting With ISO8601DateFormatter, UTC Timezone
- Date Formatting With ISO8601DateFormatter, Local Timezone
UTC Date Format
Use DateFormatter
to parse and format a date in Swift. The default time zone for a DateFormatter
is the device’s local time, so to obtain UTC time the timeZone
value needs to be configured.
let utcDateFormatter = DateFormatter()
utcDateFormatter.dateStyle = .medium
utcDateFormatter.timeStyle = .medium
// The default timeZone on DateFormatter is the device’s
// local time zone. Set timeZone to UTC to get UTC time.
utcDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
// Printing a Date
let date = Date()
print(utcDateFormatter.string(from: date))
// Parsing a string representing a date
let dateString = "May 31, 2020 at 4:32:27 AM"
let utcDate = utcDateFormatter.date(from: dateString)
Local Timezone Date Format
No configuration is required for a DateFormatter
to parse and format a date in local time.
let localDateFormatter = DateFormatter()
localDateFormatter.dateStyle = .medium
localDateFormatter.timeStyle = .medium
// No timeZone configuration is required to obtain the
// local time from DateFormatter.
// Printing a Date
let date = Date()
print(localDateFormatter.string(from: date))
// Parsing a string representing a date
let dateString = "May 30, 2020 at 11:32:27 PM"
let localDate = localDateFormatter.date(from: dateString)
Date Formatting With ISO8601DateFormatter, UTC Timezone
ISO8601DateFormatter
is a special DateFormatter
for parsing timestamps in ISO8601 format. For example, 2020-05-31T04:32:27Z
. By default, ISO8601DateFormatter
is configured to parse and format dates in UTC.
// The default timeZone for ISO8601DateFormatter is UTC
let utcISODateFormatter = ISO8601DateFormatter()
// Printing a Date
let date = Date()
print(utcISODateFormatter.string(from: date))
// Parsing a string timestamp representing a date
let dateString = "2020-05-31T04:32:27Z"
let utcDate = utcISODateFormatter.date(from: dateString)
Date Formatting With ISO8601DateFormatter, Local Timezone
To use a ISO8601DateFormatter
to parse and format local time, set the timeZone
parameter to TimeZone.current
.
// The default timeZone on ISO8601DateFormatter is UTC.
// Set timeZone to UTTimeZone.current to get local time.
let localISOFormatter = ISO8601DateFormatter()
localISOFormatter.timeZone = TimeZone.current
// Printing a Date
let date = Date()
print(localISOFormatter.string(from: date))
// Parsing a string timestamp representing a date
let dateString = "2020-05-30T23:32:27-05:00"
let localDate = localISOFormatter.date(from: dateString)
Date Formatting in Swift
That’s it! Configuring DateFormatter
and ISO8601DateFormatter
will allow you to parse and format dates in Swift.