How to Convert a Date to a Formatted String in Swift

Convert a Date to a Formatted String in Swift

When programming, you often need to convert a Date value into a formatted String.

Since this is a common task, here's how to convert a Date into a formatted String in Swift.

Using DateFormatter to Format Dates

The simplest way to format a Date value into a String is to use DateFormatter.

DateFormatter is a class designed to convert between Date and String, with customizable formatting options.


You can specify the format using the dateFormat property, and then call the string method to get the formatted String.

Here are some sample codes using common format patterns.

Since Date and DateFormatter is part of Foundation, you need to import Foundation.

import Foundation
  
let date = Date()

let df = DateFormatter()

df.dateFormat = "yyyy-MM-dd HH:mm:ss"
print(df.string(from: date))
// 2019-10-19 17:01:09

df.dateFormat = "yyyy/MM/dd HH:mm:ss"
print(df.string(from: date))
// 2019/10/19 17:01:09

df.dateFormat = "yy-M-d H:m:s"
print(df.string(from: date))
// 19-10-19 17:1:9

df.dateFormat = "yyyyMMddHHmmss"
print(df.string(from: date))
// 20191019170109

The result can also vary depending on the Locale you set.

import Foundation
  
let date = Date()

let df = DateFormatter()

//--------------------------------------
// Japanese Locale
//--------------------------------------
df.locale = Locale(identifier: "ja_JP")

df.dateFormat = "MM/dd/yyyy hh:mm:ss a"
print(df.string(from: date))
// 10/19/2019 05:19:25 午後

df.dateFormat = "MMM dd, yyyy E"
print(df.string(from: date))
// 10月 19, 2019 土

df.dateFormat = "MMMM dd, yyyy EEEE"
print(df.string(from: date))
// 10月 19, 2019 土曜日

//--------------------------------------
// US English Locale
//--------------------------------------
df.locale = Locale(identifier: "en_US")

df.dateFormat = "MM/dd/yyyy hh:mm:ss a"
print(df.string(from: date))
// 10/19/2019 05:19:25 PM

df.dateFormat = "MMM dd, yyyy E"
print(df.string(from: date))
// Oct 19, 2019 Sat

df.dateFormat = "MMMM dd, yyyy EEEE"
print(df.string(from: date))
// October 19, 2019 Saturday

You can even include other text directly in the format string:

import Foundation
  
let date = Date()
let df = DateFormatter()

df.locale = Locale(identifier: "ja_JP")

df.dateFormat = "現在の日時は、yyyy年MM月dd日 ah時mm分です。"
print(df.string(from: date))
// 現在の日時は、2019年10月19日 午後5時40分です。

You can also retrieve information such as the time zone or the UTC offset:

import Foundation
  
let date = Date()
let df = DateFormatter()

df.dateFormat = "z"
print(df.string(from: date))
// PDT

df.dateFormat = "zzzz"
print(df.string(from: date))
// Pacific Daylight Time

df.dateFormat = "Z"
print(df.string(from: date))
// -0700

For example, since I live in Los Angeles, the time zone is Pacific Daylight Time (PDT), which has a UTC offset of -7 hours.