Mo Code Mo Code - 1 year ago 201
Swift Question

Swift how to convert string to NSDate

I've got a date stored in my database and I want to retrieve it and display it nicely in my tableview cells.

The format it comes in from the database and stored in option1 is BO05151530

Where the first two letters have meaning in the program but are not needed for the date so I take those off using the substringFromIndex function.

So what is left is 05151530 where it represents MMddhmm

I would like to display it nicely like MM-dd @ h:mm a

For example 12-05 @ 3:45 am

Here is what I tried but unfortunately ns_date1 comes up as nil each time.

What would you suggest I do?

let date1 = option1.substringFromIndex(option1.startIndex.advancedBy(2))

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMddhhmm"

let ns_date1 = dateFormatter.dateFromString(date1)

Answer Source

Try this. you don't need to seperate BO NSDateFormatter can handle extra string

 let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "'BO'MMddHHmm"

let ns_date1 = dateFormatter.dateFromString("BO05151530")

dateFormatter.dateFormat = "'BO' MM-dd @ hh':'mm a"

let string = dateFormatter.stringFromDate(ns_date1!)