有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Joda DateTimeFormat根据默认语言环境切换“MM”和“dd”的位置

我有LocalDate,我想打印日期,以天/月为2位数字,以整年和“-”为分隔符

我当然可以用这样的东西:

DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MM-yyyy");
dtf.print(localDate);

它表明:

17-09-2012
18-09-2012
19-09-2012

但这只适用于我所在的地区,其他地区呢?例如,美国应该:

09-17-2012
09-18-2012
09-19-2012

如何做到这一点

DateTimeFormatter dtf = DateTimeFormat.shortDate();

它可以自动切换日和月的位置。 但它只打印:

(my locale):
17/9/12
18/9/12
19/9/12
(USA locale):
9/17/12
9/18/12
9/19/12

共 (1) 个答案

  1. # 1 楼答案

    DateTimeFormatter API开始:

    // print using the defaults (default locale, chronology/zone of the datetime)
    String dateStr = formatter.print(dt);
    // print using the French locale
    String dateStr = formatter.withLocale(Locale.FRENCH).print(dt);
    // print using the UTC zone
    String dateStr = formatter.withZone(DateTimeZone.UTC).print(dt);

    因此,您可以在DateTimeFormatter中使用区域设置或DateTimeZone

    然而,由于设置了一个模式,输出仍然是相同的

    您可以使用样式来定义DateTimeFormatter

    DateTimeFormatter dtf = DateTimeFormat.forStyle("M-");
    

    并用语言环境打印出来