I am using the following function format the time in my project.
func formatTime() -> String {
let dateFormatter = DateFormatter()
let tempLocale = dateFormatter.locale
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
if let callTime = callTime {
if let date = dateFormatter.date(from: callTime) {
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "MMMM dd yyyy hh:mm a"
dateFormatter.locale = tempLocale
let dateString = dateFormatter.string(from: date)
return dateString
} else {
return ""
}
} else {
return ""
}
}
For this function I am getting output
January 18 2023 04:36 PM
In my project I am English and Chinese language. After switching the language to Chinese the date string still remains same. I want to localise the month to Chinese. How to do that ?
CodePudding user response:
If you want to localize the date you need a template rather than a fixed date format.
This function takes a date string and a locale
func formatTime(callTime: String, locale: Locale?) -> String {
let dateFormatter = DateFormatter()
let tempLocale = locale ?? dateFormatter.locale
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" // no single quotes!
if let date = dateFormatter.date(from: callTime) {
dateFormatter.locale = tempLocale
dateFormatter.setLocalizedDateFormatFromTemplate("MMMMddyyyyhhmm")
return dateFormatter.string(from: date)
} else {
return ""
}
}
or simpler rather than a template or fixed date format specify dateStyle
and timeStyle
func formatTime(callTime: String, locale: Locale?) -> String {
let dateFormatter = DateFormatter()
let tempLocale = locale ?? dateFormatter.locale
dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.date(from: callTime) {
dateFormatter.locale = tempLocale
dateFormatter.timeStyle = .short
dateFormatter.dateStyle = .long
return dateFormatter.string(from: date)
} else {
return ""
}
}
Now call it with US and Chinese locale
let usDate = formatTime(callTime: "2022-01-18T13:12:00.111Z", locale: Locale(identifier: "en_US"))
print(usDate) // January 18, 2022 at 1:12 PM
let chineseDate = formatTime(callTime: "2022-01-18T13:12:00.111Z", locale: Locale(identifier: "zh_TW"))
print(chineseDate) // 2022年1月18日 下午1:12