How to localize date format in Kotlin

1 Answer

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

// Localized Date Formatting

fun main() {

    val now = LocalDateTime.now()

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

    println("--- 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/20/26
Long date  : Monday, April 20, 2026
Time       : 4:52:49 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:52

*/

 



answered 6 hours ago by avibootz
...