How can I format day and month in the locale-correct order in Java?

后端 未结 2 1613
暖寄归人
暖寄归人 2021-01-19 18:35

Is there a way to format a day and month (in compact form), but not year, in the locale-correct order in Java/Kotlin? So for English it should be \"Sep 20\" but for Swedish

相关标签:
2条回答
  • 2021-01-19 18:40

    No, sorry. I know of no Java library that will automatically turn "MMM d" around into 20 sep. for a locale that prefers the day of month before the month abbreviation.

    You may try modifying the answer by Rowi in this way:

    DateTimeFormatter ft = 
        DateTimeFormatter
        .ofLocalizedDate(FormatStyle.MEDIUM)
        .withLocale(Locale.forLanguageTag("sv-SE"))
    ;
    

    However the result is:

    20 sep. 2019

    It includes the year, which you didn’t ask for.

    An advanced solution would use the DateTimeFormatterBuilder class to build DateTimeFormatter objects.

    DateTimeFormatterBuilder
    .getLocalizedDateTimePattern(
        FormatStyle.MEDIUM, 
        null, 
        IsoChronology.INSTANCE, 
        Locale.forLanguageTag("sv-SE")
    )
    

    This returns d MMM y. Modify this string to delete the y and the space before it. Note that in other languages the y may be yy, yyyy or u and may not come last in the string. Pass your modified format pattern string to DateTimeFormatter.ofPattern.

    It may be shaky. Even if you look through the format pattern strings for all available locales, the next version of CLDR (where the strings come from) might still contain a surprise. But I think it’s the best we can do. If it were me, I’d consider throwing an exception in case I can detect that the string from getLocalizedDateTimePattern doesn’t look like one I know how to modify.

    0 讨论(0)
  • 2021-01-19 18:44

    You can do it in Java using LocalDate:

    LocalDate dt = LocalDate.parse("2019-09-20"); 
    System.out.println(dt);   
    DateTimeFormatter ft = DateTimeFormatter.ofPattern("dd MMM", new Locale("sv","SE")); 
    System.out.println(ft.format(dt));
    
    0 讨论(0)
提交回复
热议问题