kishor0011 kishor0011 - 10 months ago 43
Swift Question

2017-08-16 05:08:54 Convert String to in Date "17-Aug 13 : 30" using swift 3

I am trying to convert dateString "2017-08-16 05:08:54" to in "17-Aug 13 : 30" in this format.

func timeFromString(dateString : String) {

let inFormatter = DateFormatter()

inFormatter.locale = Locale(identifier: "en_US_POSIX")
//NSLocale(localeIdentifier: "en_US_POSIX")

inFormatter.dateFormat = "yyyy-MM-dd HH:mm"

let outFormatter = DateFormatter()
outFormatter.locale = Locale(identifier: "en_US_POSIX")
outFormatter.dateFormat = "dd-MMM hh:mm"

let date = inFormatter.date(from: dateString)!
let outStr = outFormatter.string(from: date)

}


Because date formatter is HH:mm in input.

Any help would be appreciated.
Thanks

Answer Source

The input is yyyy-MM-dd hh:mm:ss and the output is dd-MMM HH:mm.So do like

    let outFormatter = DateFormatter()
    // set the input format
    outFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
    // convert your string to date
    let date = outFormatter.date(from: "2017-08-16 05:08:54")!
    // set the output format 
     outFormatter.dateFormat = "dd-MMM HH : mm"
    // convert your date to expected output string
    let outStr = outFormatter.string(from: date)
    print(outStr) // -> outputs 16-Aug 05 : 08  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download