简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM