Permalink

This article is part of a collection of articles about Swift Basics, where I try to explain different parts of Swift development in a more understandable way.


While doing some development in Swift, using Dates and DateFormatters, I found the task of going through every format option quite boring. So this is a quick "cheatsheet", that anyone can use to identify what style of Date/Time they want to display, and also the code to get it.

Of course, you first need to create a Date object, which used in this way will generate the current date/time. Then you will also need a DateFormatter object, which handles the formatting, and is used to output the result into a usable String.

    let date = Date()
    let dateFormatter = DateFormatter()

Date

Full Date

Output: Wednesday, March 8, 2017

Code:

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .full
    let stringOutput = dateFormatter.string(from: date)

Long Date

Output: March 8, 2017

Code:

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .long
    let stringOutput = dateFormatter.string(from: date)

Medium Date

Output: Mar 8, 2017

Code:

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium
    let stringOutput = dateFormatter.string(from: date)

Short Date

Output: 3/8/17

Code:

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .short
    let stringOutput = dateFormatter.string(from: date)

Time

Full Time

Output: 1:26:32 PM Greenwich Mean Time

Code:

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = .full
    let stringOutput = dateFormatter.string(from: date)

Long Time

Output: 1:26:32 PM GMT

Code:

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = .long
    let stringOutput = dateFormatter.string(from: date)

Medium Time

Output: 1:26:32 PM

Code:

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = .medium
    let stringOutput = dateFormatter.string(from: date)

Short Time

Output: 1:26 PM

Code:

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = .short
    let stringOutput = dateFormatter.string(from: date)

Date and Time

You can of course, use the dateFormat and timeFormat together to output the date and time in the same string.

Here is an example:

Output: March 8, 2017 at 1:37 PM

Code:

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .long
    dateFormatter.timeStyle = .short
    let stringOutput = dateFormatter.string(from: date)

Download

I've made a Swift Playground containing all of the formats for date and time, which you can use yourself by copying the code from GitHub.