DateTimeFormatter does not work with LLLL template in en locale

With rulocale, returns the full name of the month ( ), but only with the ennumber ( 2).

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("LLLL", new Locale("ru"));
LocalDate.now().format(formatter);

MMMMworks with en, but does not work with ru(you need a case).

How to get the full month name for all locales?

+4
source share
2 answers

JDK-8114833 Java-8. , Java-9 ( ). , , () , :

private static final Set<String> LANGUAGES_WITH_STANDALONE_CASE;

static {
    Set<String> set = new HashSet<>();
    set.add("ru");

    // add more languages which require LLLL-pattern (for example other slavish languages)
    LANGUAGES_WITH_STANDALONE_CASE = Collections.unmodifiableSet(set);
}

public static void main(String[] args) throws Exception {

    Locale locale = new Locale("en");

    DateTimeFormatter formatter =
      DateTimeFormatter.ofPattern(
        LANGUAGES_WITH_STANDALONE_CASE.contains(locale.getLanguage()) 
          ? "LLLL" : "MMMM",
        locale
      );
    System.out.println(LocalDate.now().format(formatter));

    // ru => 
    // en => February
}

, , , . JSR-310 (aka java.time -API).

, SimpleDateFormat ( Java-8) :

    Locale locale = new Locale("en");

    SimpleDateFormat sdf = new SimpleDateFormat("LLLL", locale);
    System.out.println(sdf.format(new Date()));

, , java.util.Date.

, "L" API- . , Time4J. , , Time4J JSR-310 ( ):

    Locale locale = new Locale("ru");

    ChronoFormatter<LocalDate> formatter =
        ChronoFormatter.ofPattern(
            "LLLL",
            PatternType.CLDR,
            locale,
            PlainDate.axis(TemporalType.LOCAL_DATE)
        );
    System.out.println(formatter.format(LocalDate.now()));

    // ru => 
    // en => February

ConcurrentHashMap .

+2

MM LL MMMM/ LLLL

System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("MM", new Locale("ru"))));
System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("MM", new Locale("en"))));

02

0

Source: https://habr.com/ru/post/1669802/


All Articles