APK APPS APK APPS - 4 months ago 102x
iOS Question

Convert TimeString yyyy-mm-dd HH:mm:ss to NSDate Time HH:mm AM/PM in swift

I want to convert Time string to NSDate Time into HH:mm: a format. I have a code right now

let defaultStartTime = json!["start_schedule_datetime"] as? String
let defaultEndTime = json!["end_schedule_datetime"] as? String


dispatch_async(dispatch_get_main_queue(), {

let dtf = NSDateFormatter()
dtf.timeZone = NSTimeZone(name: "UTC")
dtf.dateFormat = "HH:mm a"

let defaultStartdate : NSDate = dtf.dateFromString(defaultStartTime!)!
let defaultEnddate : NSDate = dtf.dateFromString(defaultEndTime!)!


self.startTime.date = defaultStartdate
self.endTime.date = defaultEnddate



start_schedule_datetime = 2016-05-27 13:35:00
end_schedule_datetime = 2016-05-27 19:35:00

Here i want time into HH:mm a. But when i am trying to do that i am getting

fatal error: unexpectedly found nil while unwrapping an Optional value

Can any one please help me here. Thank you


You can do something like,

 let str: String = "2016-05-27 13:35:00"
    let formt: NSDateFormatter = NSDateFormatter()
    formt.dateFormat = "yyyy-MM-dd HH:mm:ss"
    var date: NSDate = formt.dateFromString(str)!

Print that date, It will your desired date. your dateformatter and your string should be in same format. so your date format must be yyyy-MM-dd HH:mm:ss according to your date you write in question.

Hope this will help :)