Swift : How to convert String to string with time format?
You need 2 NSDateFormatter
s, one for dateFromString
, one for stringFromDate
let inFormatter = NSDateFormatter()
inFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
inFormatter.dateFormat = "HH:mm"
let outFormatter = NSDateFormatter()
outFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
outFormatter.dateFormat = "hh:mm"
let inStr = "16:50"
let date = inFormatter.dateFromString(inStr)!
let outStr = outFormatter.stringFromDate(date)
println(outStr) // -> outputs 04:50
2020 | SWIFT 5.1:
func dateTimeChangeFormat(str stringWithDate: String, inDateFormat: String, outDateFormat: String) -> String {
let inFormatter = DateFormatter()
inFormatter.locale = Locale(identifier: "en_US_POSIX")
inFormatter.dateFormat = inDateFormat
let outFormatter = DateFormatter()
outFormatter.locale = Locale(identifier: "en_US_POSIX")
outFormatter.dateFormat = outDateFormat
let inStr = stringWithDate
let date = inFormatter.date(from: inStr)!
return outFormatter.string(from: date)
}
usage:
let outStr = dateTimeChangeFormat(str: "16:50",
inDateFormat: "HH:mm",
outDateFormat: "hh:mm")
println(outStr) // -> outputs 04:50