具有更多控制力的本地化日期/时间

Bry*_*yan 5 java android localization threetenbp

我正在使用 ThreeTen-Backport (特别是ThreeTenABP)来显示项目中的时间戳。我希望显示的时间戳以本地化格式显示(基于Locale系统的);使用以下任一方法都很容易DateTimeFormatter.ofLocalizedDateTime()

\n\n
DateTimeFormatter formatter = DateTimeFormatter\n        .ofLocalizedDateTime(FormatStyle.LONG)\n        .withLocale(Locale.getDefault())\n        .withZone(ZoneId.systemDefault());\n\nString timestamp = formatter.format(Instant.now());\n
Run Code Online (Sandbox Code Playgroud)\n\n

FormatStyle问题是我对只有四种类型(SHORTMEDIUMLONG、 )的格式化程序的输出没有太多控制FULL。我很好奇是否有一种方法可以对输出进行更精细的控制,而不丢失本地化格式。

\n\n
\n\n

timestamp使用前面的代码,区域设置的结果"en_US"将是:

\n\n
"January 23, 2017 1:28:37 PM EST"\n
Run Code Online (Sandbox Code Playgroud)\n\n

虽然区域设置的结果"ja_JP"是:

\n\n
"2017\xe5\xb9\xb41\xe6\x9c\x8823\xe6\x97\xa5 13:28:37 GMT-5:00"\n
Run Code Online (Sandbox Code Playgroud)\n\n

正如您所看到的,每个区域设置都使用特定的模式,并使用默认的 12 或 24 小时格式。我想保留本地化模式,但更改一些内容,例如是否显示时区,或者是否使用 12 小时或 24 小时格式。

\n\n

例如; 如果我可以将两个区域设置设置为使用 12 小时格式,并删除时区;结果如下所示:

\n\n
"January 23, 2017 1:28:37 PM"\n\n"2017\xe5\xb9\xb41\xe6\x9c\x8823\xe6\x97\xa5 1:28:37\xe5\x8d\x88\xe5\xbe\x8c"\n
Run Code Online (Sandbox Code Playgroud)\n

Pro*_*ock 1

Locale您可以获取with的格式字符串DateTimeFormatterBuilder.getLocalizedDateTimePattern。一旦获得该字符串,就可以使用该DateTimeFormatter.ofPattern方法对其进行操作。

    String fr = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.LONG, FormatStyle.FULL, IsoChronology.INSTANCE, Locale.FRANCE);
    //d MMMM yyyy HH' h 'mm z
    String ge = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.LONG, FormatStyle.FULL, IsoChronology.INSTANCE, Locale.GERMAN);
    //d. MMMM yyyy HH:mm' Uhr 'z
    String ca = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.LONG, FormatStyle.FULL, IsoChronology.INSTANCE, Locale.CANADA);
    //MMMM d, yyyy h:mm:ss 'o''clock' a z
    String en = DateTimeFormatterBuilder.getLocalizedDateTimePattern(FormatStyle.LONG, FormatStyle.FULL, IsoChronology.INSTANCE, Locale.ENGLISH);
    //MMMM d, yyyy h:mm:ss a z
Run Code Online (Sandbox Code Playgroud)

DateTimeFormatter可以使用符号字符和Pattern 方法指定日期的各个单位。每个单位使用的符号字符数量也会影响显示的内容:

  • M将为您提供月份的数字。
  • MM即使月份小于 10,也会得到两位数的月份。
  • MMM应该给你月份名称。

请参阅文档中的“格式化和解析模式”部分 DateTimeFormatter

下面的模式为您提供了四位数的年份、两位数的月份和两位数的日期。

LocalDate localDate = LocalDate.now(); //For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String formattedString = localDate.format(formatter);
Run Code Online (Sandbox Code Playgroud)