format a date to a localized string in swift

To display a date as a localized string in Swift, you can use the DateFormatter class. Here's an example that shows how to create a date formatter that displays the date in the user's preferred format and language:

main.swift
let date = Date()
let dateFormatter = DateFormatter()

dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
dateFormatter.locale = Locale.current

let localizedDateString = dateFormatter.string(from: date)
print(localizedDateString)
246 chars
10 lines

In this example, we create a new DateFormatter object and set its dateStyle and timeStyle properties to .short. We also set the locale property to Locale.current to use the user's preferred language and region settings.

Finally, we call the string(from: date) method on the formatter object to get the localized date string, which we print to the console.

If you're using SwiftUI, you can use the Text view's localizedString(key:tableName:bundle:comment:) method to display the localized date string:

main.swift
let date = Date()
let dateFormatter = DateFormatter()

dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
dateFormatter.locale = Locale.current

let localizedDateString = dateFormatter.string(from: date)

Text(localizedDateString.localizedStringKey())
267 chars
11 lines

Here, we create a localized string key using the localizedStringKey() method and pass it to the Text view. SwiftUI automatically looks up the string in the app's localization table and displays the localized string.

gistlibby LogSnag