How to convert date to string & vice versa in Swift

 

This tutorial is updated for X code 7.3 & swift 2.2

This is very commonly used in iOS apps that use date. Absolute value of date is difficult to understand. And apps may need to show date in different formats for each situation. Also date need to be converted into string before we can display in app. We are going to kill 3 birds in one stone.

We are going to learn two methods to convert date to string. First is to convert in pre formatted date. Because date is used very often there are few readymade date formats available to use out of the box. In second method we are going to create custom format for the date & time.

Lets begin with first method

In playground add following code

let dateformatter = NSDateFormatter()

dateformatter.dateStyle = NSDateFormatterStyle.ShortStyle

dateformatter.timeStyle = NSDateFormatterStyle.ShortStyle

let now = dateformatter.stringFromDate(NSDate())

The output for this is as follows

Screen Shot 2015-05-11 at 11.08.47 pm

The other variations are as follows. Feel free to test them in swift playground

DateStyle or TimeStyle DateTime
NoStyle
ShortStyle1/27/101:00 PM
MediumStyleJan 27, 20101:00:00 PM
LongStyleJanuary 27, 20101:00:00 PM EST
FullStyleWednesday, January 27, 20101:00:00 PM Eastern Standard Time

By default its showing date & time in users local time zone. If you want to show date at different time zone then add following line

dateformatter.timeZone = NSTimeZone(name: “America/New_York”)

To learn how to name time zone see wikipedia tutorial here.

Now let start with second method for creating custom formatted date & time.

In playground add following code

let dateformatter = NSDateFormatter()

dateformatter.dateFormat = “MM/dd/yy h:mm a Z”

let now = dateformatter.stringFromDate(NSDate())

The output for this is as follows

Screen Shot 2015-05-12 at 1.18.11 am

The other variations are as follows. Any string between ‘ (single quote) is printed as is.

Format StringOutput
MM/dd/yy01/09/07
MMM dd, yyyyJan 09, 2007
E MMM dd, yyyyTue Jan 09, 2007
EEEE MMMM dd, yyyy’ at ‘h:mm a zz.Tuesday January 09, 2007 at 10:00 AM PST.
EEEE MMMM dd, yyyy’ at ‘h:mm a zzzz.Tuesday January 09, 2007 at 10 AM Pacific Standard Time.
‘Year: ‘y’ Month: ‘M’ Day: ‘dYear: 2007 Month: 1 Day: 9

Challenge : Convert string to date

Now we are going to learn how to convert string to date.

In playground add following code

let dateformatter = NSDateFormatter()</p>

dateformatter.dateFormat = “MM/dd/yy h:mm a Z”</p>

let now = dateformatter.dateFromString(“2/5/07 12:00 AM 0500”)

The output is in UTC so it will be different

Screen Shot 2015-05-12 at 1.14.27 am

For other variation refer to previous chart of custom format from date to string.

Total 20 Votes
7

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?