Reputation: 173
Is there a way to show date in a language other than English (especially the day in a week) in Swift?
I already have this DateFormatter
to show the day in a week, but it only shows it in English:
var today = Date()
static let weekDayFormat: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh")
formatter.dateFormat = "E"
return formatter
}()
If I write Text("\(today, formatter: Self.weekDayFormat)")
, it will show "Sat".
However, I need it to show it in Chinese. Even if I tried set formatter.locale = Locale(identifier: "zh")
and other identifier of Chinese, it always output an English result. I think it might just be that the English acronym of weekdays is commonly recognized, but my client wants it to show Chinese.
Upvotes: 4
Views: 6597
Reputation: 3505
This is an interesting case. Did you take the example from Hacking with Swift? ;) https://www.hackingwithswift.com/quick-start/swiftui/how-to-format-text-inside-text-views
I use setLocalizedDateFormatFromTemplate
because preferred by Apple as in WWDC:
https://developer.apple.com/videos/play/wwdc2020/10160/
I had the same problem, it would not work with the locale parameter inside the static var and I solved it in this way:
import SwiftUI
struct test: View {
var today: String {
let date = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh")
//or formatter.locale = .autoupdatingCurrent
formatter.setLocalizedDateFormatFromTemplate("E")
return formatter.string(from: date)
}
// or edited from Leo Dabus
static let weekDay: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "zh")
// or formatter.locale = .autoupdatingCurrent
formatter.setLocalizedDateFormatFromTemplate("E")
return formatter
}()
var body: some View {
Text("\(today) \(Self.weekDay.string(from: Date()))")
}
}
struct test_Previews: PreviewProvider {
static var previews: some View {
test()
}
}
formatter.locale = .autoupdatingCurrent
will auto update according to changes to the current language setting of the simulator or device in setting/general/language.
But don't forget to add those languages in your project!
https://developer.apple.com/forums/thread/97252?answerId=295557022#295557022
Upvotes: 0
Reputation: 236340
import SwiftUI
struct ContentView: View {
var body: some View {
Text(Formatter.weekDay.string(from: Date())).padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
extension Formatter {
static let weekDay: DateFormatter = {
let formatter = DateFormatter()
// you can use a fixed language locale
formatter.locale = Locale(identifier: "zh")
// or use the current locale
// formatter.locale = .current
// and for standalone local day of week use ccc instead of E
formatter.dateFormat = "ccc"
return formatter
}()
}
Upvotes: 7