One of the strongest classes of the Foundation framework undoubtly is NSDateFormatter. With NSDateFormatter, one can easily convert a date object into strings with various formats that human can read.

NSDate

NSDate is the class from Foundation framework that is used to represent dates. NSDateFormatter and NSDate objects are in cooperation for us humans to understand the dates.

To create a date object that contains current date and time simply create an NSDate object. In Objective-C:

NSDate *currentDate = [NSDate date];

And in Swift:

let currentDate = NSDate()

There are a few more ways to create date objects using time intervals. Time intervals are simply seconds. Also NSTimeInterval is simply a typedefed double.

There are four initializer methods defined in NSDate which takes a time interval as a parameter. One of them is:

let date = NSDate(timeIntervalSince1970: 1426003200)

You can have a look at its discussion and other forms in the documentation.

NSDateFormatter

Date formatters are expensive objects. It’s suggested to create them once and use the same formatter object for repeated tasks.

Simply create a date formatter object:

let dateFormatter = NSDateFormatter()

and set its date formatting style:

dateFormatter.dateStyle = .MediumStyle

Then give it a date object to format it:

dateFormatter.stringFromDate(date)

You’ll get the following output:

“Mar 10, 2015”

There are a few more predefined formats like .MediumStyle. They are NoStyle, ShortStyle, LongStyle, and FullStyle. Try them out!

Custom Formats

You can also define your own formats. Just provide NSDateFormatter a format string and the rest is the same procedure.

dateFormatter.dateFormat = “HH:mm, d MMM yyyy”

With this format, you can get a string like:

“18:00, 10 Mar 2015”

In the format string, writing one more M for the month will print the whole name of the month. Like:

dateFormatter.dateFormat = “HH:mm, d MMMM yyyy”

will give us:

“18:00, 10 March 2015”

What about localization?

NSLocale is another partner of NSDateFormatter. You can provide a locale for the language you want and date formatter will format the date according to it. For example:

dateFormatter.locale = NSLocale(localeIdentifier:”tr”)

will give us:

“18:00, 10 Mart 2015”

and

dateFormatter.locale = NSLocale(“ru”)

will give us:

“18:00, 10 марта 2015”

You can also provide the locale which is set in system settings like:

dateFormatter.locale = NSLocale.currentLocale()

So that you can have a date formatted with the current locale of the user’s choice!

Conclusion

These are the basic tips & tricks about date formatting on iOS!

And you can find the playground file of this post here.