Search code examples
iosswiftswift3nsdateformatter

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-17 12:08:00" to in "17-Aug 17 : 38" 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)

}

I just want to add 5:30 also.

Because date formatter is HH:mm in input? So I am not getting exact output? And if yes, then why?


Solution

  • 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