Topics

#286: DateFormatter Basics 📆

Topics

Formatting dates and times is one of those common tasks we all have to do in almost every app. Today we'll take a look at how to use Foundation's solution for this: DateFormatter.

DateFormatters are incredibly powerful. Their core purpose is transforming Dates into Strings and Strings into Dates. They handle things like localization for us under the hood. Let's try one out.

We'll create a new formatter:

let formatter = DateFormatter()

Then we'll need to set a "format" on it. This is a string of characters that represent the date we're going to try to parse or render. Often these appear as one or more repeated series of letters like:

formatter.dateFormat = "MMM yyyy"

To see a rendered date string using this format, we can ask for one like this:

formatter.string(from: Date()) // "Jan 2017"

We can play around with the format for different results:

formatter.dateFormat = "MMMM yy"
formatter.string(from: Date()) // "January 17"

Neat. Let's try going the other way. We'll pass in a string, and ask our DateFormatter to parse it into a Date for us.

formatter.dateFormat = "MMMM yy"
formatter.date(from: "February 28")

// "Feb 1, 2028, 12:00 AM"

Very cool.

A couple of pro tips before we go:

The first is that DateFormatters have historically been heavy-weight objects to create. Performance has definitely improved over the years, but if we can, it's probably a good idea to keep one around instead of creating on the fly each time we need it. (For example we wouldn't want to be creating a new DateFormatter inside a UITableView or UICollectionView "cell for row" style delegate function).

The second is that these format strings are opaque and hard to understand at a glance. To solve this, friend of the show (and creator of the awesome NSScreencasts) Ben Scheirman has created a site called nsdateformatter.com.

There we can not only find easy, glance-able examples and references for all the different date format tokens, but we can also test out formats right there in the browser! Super handy.

We've only scratched the surface of what Foundation is capable of when it comes to Dates. Tune in tomorrow to learn more.