I want get current time in 12 hour format.I want format if time is 18:36 then it should be like 06:35 PM. for this purpose i have used below code but it just don't give me required format.I get format like this.
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date22 = dateFormatter.string(from: date)
Check out this date formatting guide. & this site.
let dateAsString = "6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.dateFromString(dateAsString)
dateFormatter.dateFormat = "HH:mm"
let date24 = dateFormatter.stringFromDate(date!)
I also had the same problem(from my backend dateString is coming in 24 hours format and also in UTC), so I created a function it is working perfectly. See this function:-
func getRequiredFormat(dateStrInTwentyFourHourFomat: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let newDate = dateFormatter.date(from: dateStrInTwentyFourHourFomat) {
let timeFormat = DateFormatter()
timeFormat.timeZone = TimeZone.autoupdatingCurrent
timeFormat.locale = Locale(identifier: "en_US_POSIX")
timeFormat.dateFormat = "hh:mm a"
let requiredStr = timeFormat.string(from: newDate)
return requiredStr
} else {
return nil
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With