Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: show Date() in other language

Tags:

date

swift

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.

like image 497
Charlotte L. Avatar asked Sep 17 '25 03:09

Charlotte L.


1 Answers

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
    }()
}
like image 62
Leo Dabus Avatar answered Sep 19 '25 14:09

Leo Dabus