How to localize date format in Swift

1 Answer

0 votes
// Localized Date Formatting

import Foundation

// Current date/time
let now = Date()

// 1. Localized date using the system locale
let systemLocale = Locale.current

print("--- Using system locale: \(systemLocale.identifier) ---")

let shortDateFormatter = DateFormatter()
shortDateFormatter.locale = systemLocale
shortDateFormatter.dateStyle = .short
print("Short date :", shortDateFormatter.string(from: now))

let longDateFormatter = DateFormatter()
longDateFormatter.locale = systemLocale
longDateFormatter.dateStyle = .full
print("Long date  :", longDateFormatter.string(from: now))

let timeFormatter = DateFormatter()
timeFormatter.locale = systemLocale
timeFormatter.timeStyle = .medium
print("Time       :", timeFormatter.string(from: now))

let weekdayFormatter = DateFormatter()
weekdayFormatter.locale = systemLocale
weekdayFormatter.dateFormat = "EEEE"
print("Weekday    :", weekdayFormatter.string(from: now))

let monthFormatter = DateFormatter()
monthFormatter.locale = systemLocale
monthFormatter.dateFormat = "MMMM"
print("Month name :", monthFormatter.string(from: now))


// 2. Localized date using a specific locale (French example)
let fr = Locale(identifier: "fr_FR")

print("\n--- Using French locale ---")

let frShort = DateFormatter()
frShort.locale = fr
frShort.dateStyle = .short
print("Short date :", frShort.string(from: now))

let frLong = DateFormatter()
frLong.locale = fr
frLong.dateStyle = .full
print("Long date  :", frLong.string(from: now))

let frWeekday = DateFormatter()
frWeekday.locale = fr
frWeekday.dateFormat = "EEEE"
print("Weekday    :", frWeekday.string(from: now))

let frMonth = DateFormatter()
frMonth.locale = fr
frMonth.dateFormat = "MMMM"
print("Month name :", frMonth.string(from: now))


// 3. Custom localized pattern (weekday + day + month + year + time)
let customFr = DateFormatter()
customFr.locale = fr
customFr.dateFormat = "EEE d MMMM yyyy 'à' HH:mm"

print("\n--- Custom French format ---")
print(customFr.string(from: now))



/*
run:

--- Using system locale: en_US ---
Short date : 4/20/26
Long date  : Monday, April 20, 2026
Time       : 4:59:01 AM
Weekday    : Monday
Month name : April

--- Using French locale ---
Short date : 20/04/2026
Long date  : lundi 20 avril 2026
Weekday    : lundi
Month name : avril

--- Custom French format ---
lun. 20 avril 2026 à 04:59

*/

 



answered 6 hours ago by avibootz
...