How to localize date format in Scala

1 Answer

0 votes
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.Locale

object LocalizedDateExample {
  def main(args: Array[String]): Unit = {

    // Current date/time
    val now = LocalDateTime.now()

    // 1. Localized date using the system locale
    val systemLocale = Locale.getDefault

    println(s"--- Using system locale: $systemLocale ---")

    println("Short date : " +
      now.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(systemLocale)))

    println("Long date  : " +
      now.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(systemLocale)))

    println("Time       : " +
      now.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM).withLocale(systemLocale)))

    println("Weekday    : " +
      now.format(DateTimeFormatter.ofPattern("EEEE", systemLocale)))

    println("Month name : " +
      now.format(DateTimeFormatter.ofPattern("MMMM", systemLocale)))


    // 2. Localized date using a specific locale (French example)
    val fr = Locale.FRANCE

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

    println("Short date : " +
      now.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(fr)))

    println("Long date  : " +
      now.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(fr)))

    println("Weekday    : " +
      now.format(DateTimeFormatter.ofPattern("EEEE", fr)))

    println("Month name : " +
      now.format(DateTimeFormatter.ofPattern("MMMM", fr)))


    // 3. Custom localized pattern (weekday + day + month + year + time)
    val customFr = DateTimeFormatter.ofPattern("EEE d MMMM yyyy 'à' HH:mm", fr)

    println("\n--- Custom French format ---")
    println(now.format(customFr))
  }
}



/*
run:

--- Using system locale: en_US ---
Short date : 4/19/26
Long date  : Sunday, April 19, 2026
Time       : 6:16:44?PM
Weekday    : Sunday
Month name : April

--- Using French locale ---
Short date : 19/04/2026
Long date  : dimanche 19 avril 2026
Weekday    : dimanche
Month name : avril

--- Custom French format ---
dim. 19 avril 2026 ? 18:16

*/

 



answered 6 hours ago by avibootz
...