Thursday, December 17, 2015

Converting Date to a String or String to a Date in Swift

A very common use case many of you will come across is converting a NSDate object to a String object or vice versa. When I came across a use case where I had to convert a Date to String in my iOS app written in Swift I did an online search but it was hard to find a good example of the correct solution so I hope to provide an easy reference for anyone who is looking to implement the same.

Scenario 1: Converting Date to String

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "Y/M/d"
let duedateString = dateFormatter.stringFromDate(dueDatePicker.date)

Note the format "Y/M/d" used in the second line above is a Date Format value that defines how the date is represented in the String format. You can find a good resource here for the various values you can use to define the date format.

Also note that the dueDatePicker.date value used in the last line of the code above is referencing a Date Picker in the UI of my app, however, you can simply replace it with any Date object.

Let's say the user picked 12/25/2015 as the date, the value of duedateString at the end of the code's execution will be "2015/12/25" because of the format we used which says give me a string in Y/M/d format.

Scenario 2: Converting String to Date

This is even simpler and requires only 2 lines of code.

let dateFormatter = NSDateFormatter()
let dueDate = dateFormatter.dateFromString("12/17/2015")

Hope this helps!

Regards,