SimpleDateFormat pattern based on locale, but forcing a 4-digit year

前端 未结 4 1611

I need to build a date format like dd/MM/yyyy. It\'s almost like DateFormat.SHORT, but contains 4 year digits.

I try to implement it with

4条回答
  •  终归单人心
    2021-02-15 17:31

    java.time

    Here’s the modern answer. IMHO these days no one should struggle with the long outdated DateFormat and SimpleDateFormat classes. Their replacement came out in the modern Java date & time API early in 2014, the java.time classes.

    I am just applying the idea from Happier’s answer to the modern classes.

    The DateTimeFormatterBuilder.getLocalizedDateTimePattern method generates a formatting pattern for date and time styles for a Locale. We manipulate the resulting pattern string to force the 4-digit year.

    LocalDate date = LocalDate.of( 2017, Month.JULY, 18 );
    
    String formatPattern =
        DateTimeFormatterBuilder.getLocalizedDateTimePattern(
            FormatStyle.SHORT, 
            null, 
            IsoChronology.INSTANCE, 
            userLocale);
    formatPattern = formatPattern.replaceAll("\\byy\\b", "yyyy");
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern, userLocale);
    
    String output = date.format(formatter);
    

    Example output:

    • For Locale.US: 7/18/2017.
    • For each of UK, FRANCE, GERMANY and ITALY: 18/07/2017.

    DateTimeFormatterBuilder allows us to get the localized format pattern string directly, without getting a formatter first, that’s convenient here. The first argument to getLocalizedDateTimePattern() is the date format style. null as second argument indicates that we don’t want any time format included. In my test I used a LocalDate for date, but the code should work for the other modern date types too (LocalDateTime, OffsetDateTime and ZonedDateTime).

提交回复
热议问题