DateTimeFormatter不能与en语言环境中的LLLL模式一起使用

时间:2017-02-15 09:35:06

标签: java date-format

ru区域设置返回完整月份名称(Февраль),但只有en个号码(2)。

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

MMMMen合作,但无法与ru合作(需要提名案例)。

如何获取所有区域设置的完整月份名称?

2 个答案:

答案 0 :(得分:2)

遗憾的是,{8}尚未解决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样式和更好的性能特征。例如,您可以使用我的库the related bug issue JDK-8114833。这里演示了后一种情况,它还展示了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中。

答案 1 :(得分:-1)

对于主格,您必须将模式设置为 MM LL ,而不是 MMMM / LLLL < / p>

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

相关问题