SlopTonio
SlopTonio

Reputation: 1105

String to NSDate vice versa then into a UILabel

GOAL: I want my string to be date formatted and put inside a label.

Current code:

let dateString           = "2015-10-09 17:41:14"
let dateFormatter        = NSDateFormatter()
dateFormatter.dateFormat = "MMMM d, yyyy | hh:mm a" 
let date                 = dateFormatter.dateFromString(dateString)
//FOUND NIL HERE
let NewString            = dateFormatter.stringFromDate(date!)
Date.text                =  NewString

The code above works if I do NSDate() but not if I use my own string?

Upvotes: 1

Views: 154

Answers (1)

Midhun MP
Midhun MP

Reputation: 107131

You are using wrong date format to convert the string to date and it returns a nil date because of that. First you need to use the exact date format to convert the string to date then set your date formatter style to get it back as string in your desired format.

Change your code like:

let dateString           = "2015-10-09 17:41:14"
let dateFormatter        = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date                 = dateFormatter.dateFromString(dateString)
dateFormatter.dateFormat = "MMMM d, yyyy | hh:mm a"
let resultString         = dateFormatter.stringFromDate(date!)
print(resultString) // October 9, 2015 | 05:41 PM

Upvotes: 2

Related Questions