Swift program to convert a string to date

Swift program to convert a string to date:

In swift, it is pretty easy to convert a string to date. DateFormatter class is used to convert a valid string to Date object. We need to define the date format in the DateFormatter for different types of date strings. In this post, we will learn how to do the date to string conversion in Swift with examples.

Simple string to date conversion:

Let’s take a look at the below example:

import Foundation

let dateString = "01/12/2020"
let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "dd/MM/yy"

let date = dateFormatter.date(from: dateString)

print(date)

Here,

  • we need to import Foundation to use DateFormatter.
  • dateFormat is the format of the string date. It uses unicode technical standard format.
  • dateFormatter.date returns the date. It is an optional value.

For the above program, it will print:

Optional(2020-10-31 18:30:00 +0000)

Another complex example:

import Foundation

let dateString = "2020 Jan 30, 11:10:30"
let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yy MMM d, hh:mm:ss"

let date = dateFormatter.date(from: dateString)

print(date)

Swift string to date

Invalid dateFormat string:

For an invalid dateFormat string or if the date format string doesn’t match with the date string, it will return nil.

import Foundation

let dateString = "2020/01/01"
let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yy MMM d, hh:mm:ss"

let date = dateFormatter.date(from: dateString)

print(date)

It will print nil.

You might also like: