1
    LocalDateTime today = LocalDateTime.now();
    String timeMedium = today.format(DateTimeFormatter
            .ofLocalizedTime(FormatStyle.MEDIUM));
    System.out.println("timeMedium = " + timeMedium);

在这段代码中,我们期望输出类似的东西timeMedium = 1:12:50 AM。它在许多具有相同 Java 版本 (16) 的 PC 中显示 AM/PM。该代码应与 java 8 及更高版本相同。但在我的电脑(MacOS Catalina)中,AM/PM 从未出现。下面的代码也是一样的。

    ZonedDateTime today = ZonedDateTime.now();
    String timeMedium = today.format(DateTimeFormatter
            .ofLocalizedTime(FormatStyle.LONG));
    System.out.println("timeMedium = " + timeMedium);

输出将是这样的timeMedium = 1:11:35 a.m. EDT。它在 Ubuntu 20.04 中运行良好。但在我的 Mac 中,它显示没有 AM/PM。

注意 - 我的电脑设置为 12 小时时间格式。

4

1 回答 1

0

语言环境

这是使用所需语言环境的问题。Java 不会采用底层操作系统(在您的情况下为 macOS)的 12 小时或 24 小时设置。它经常选择操作系统的语言环境,但不能保证总是这样做。因此,防弹解决方案是在 Java 代码中指定语言环境。例如孟加拉语语言环境:

    ZonedDateTime today = ZonedDateTime.now(ZoneId.of("Asia/Dhaka"));
    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG)
                    .withLocale(Locale.forLanguageTag("bn-BD"));
    String timeLong = today.format(timeFormatter);
    System.out.println("timeLong = " + timeLong);

示例输出:

时间长 = 上午 9 点 11 分 57 秒 BDT

链接(谢谢,Andreas):如何在 JVM 中设置默认语言环境?

于 2021-05-18T03:12:45.693 回答