Formatting dates and times are one of the common tasks we all have to do in almost all apps. Today we take a look at how to use Foundation's solution for this:
DateFormatter s is incredibly powerful. Your main purpose is to transform
Date s to
String s and
String s to
Date p. They handle things like location for us under the hood . Let's try one out.
We make a new format:
la formats = DateFormatter ()
Then we have to put a format on it. This is a string of characters like represents the date we will try to analyze or render. Often they look like one or more repeating boxes like:
format . dateFormat = "MMM yyyy"
In order to see a rendered data string using this format, ( from : Date ())
[MM] 19659011] ( from : Date ()) // "17. January 19659012] Let's try to go the other way. We pass by a string and ask our
DateFormatter to analyze it for a
Date for us.
] format . dateformat =  : "February 28" ) // "1. February 19659017] "MMMM yy formats . date 2028, 12:00"
A couple of tips before we go:
The first is that
DateFormatters have historically been heavyweight 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 the fly every time we need it. (For example, we will not create a new
DateFormatter inside a
UICollectionView "cell by line" style delegate function ]).
The other is that these format strings are opaque and difficult to understand in a moment. To solve this, friend of the show (and creator of the amazing NSScreencasts) Ben Scheirman has created a site called nsdateformatter.com.
We can not only find simple, flashy examples and references for all the different date format tokens, but we can also test formats there in the browser! Super handy.
We have only scratched the surface of what Foundation is able to
Date p. Set tomorrow to learn more.