In Bite #287, we built a small extension to Date to allow us to format relative date strings like "10 minutes ago". We used a bunch of if statements and built our final String. This was a nice way to learn about working with DateComponents, but it turns out 🛎Foundation actually provides a class to do something similar, and it's much more powerful.
Today we'll continue our look at Foundation's date and time-related functionality with DateComponentsFormatter. Let's dive in.
Much like its cousin DateFormatter (Bite #286), DateComponentsFormatter is all about converting a TimeInterval or DateComponents into a nicely formatted, human-readable String. (Note: It doesn't support parsing Strings yet. Conversions are a one way trip for now).
In Bite #286, we looked at the basics of using DateFormatters to transform Dates into Strings.
Today we'll explore another common use case of Dates in our apps: "relative" date strings.
Think "2 days ago", "10 minutes ago", "Yesterday", and "Just now". Representing timestamps this way has become common, and it can help our users more quickly understand how old a piece of content is.
Let's add this functionality to our app by extending Date to give it a new computed property to do this.
We'll begin by adding a new File to our Xcode Project. We'll call it Date+Relative.swift. (The Type+SomeExtensionName convention is borrowed from Objective-C.
Nice. Next, we'll need a way to calculate how much time is in between now, and self (from the extended Date's point of view). We could do a bunch of ugly math, but we've got a better way!
This is a fantastic use case for Foundation's DateComponents type. It has a function that can calculate the difference between two Dates, and provide it to us in neatly (pre-calculated) components like days, months, hours, seconds, etc.
We ask the current Calendar to please calculate the quantity of each of the components we passed in for the time between the Date we passed in as the from argument to the Date we passed into the to argument.
Beautiful. Now, the returned DateComponents type has a bunch of properties we'll use to build our relatively formatted date `String.
Finally, we'll inspect each date component (starting with most broad at the top) and return a nicely formatted String:
Doing things manually like this allows us to completely customize and control exactly how this relative date strings appear in our app.
This is fairly straightforward. We get a little fancy for the "days" component, allowing for "yesterday". We could also easily add support for future dates (i.e. "tomorrow") here as well.
All that's left to do is test it out. We can do that easily by constructing some Dates in the past, then printing our new property:
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:
letformatter=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:
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.