考虑到 GWT 中的本地化,将字符串格式化为日期

Format String into Date considering localization in GWT

我遇到的问题是我无法将格式为 "270317"(德语版)的 String 格式化为 Date

为此,我使用了 GWT。 我到目前为止是这样的:

String input = "270317";
LocaleInfo locale = null;
if (locale == null) {
    locale = LocaleInfo.getCurrentLocale();
}
date = DateTimeFormat.getFormat(input).parse(input);

结果始终是当前日期:07/28/2017

我想要实现的是获得在执行程序的国家/地区所写的日期。 如果这真的不可能,那么我宁愿这样写:03/27/2017.

要将输入 270317 解析为 Date,您必须提供预期的格式(您使用 input 作为格式,这是错误的):

String input = "270317";
Date date = DateTimeFormat.getFormat("ddMMyy").parse(input);

这将正确解析 date如果 输入格式始终为日-月-年。如果输入以本地化格式生成,那么您可以使用 DateTimeFormat.getFormat(PredefinedFormat.DATE_SHORT) 或任何其他格式 - 但这是特定于语言环境的,并且在不同环境之间可能会有很大差异。

检查您的输入以了解您是否需要使用固定格式或本地化格式。

解析日期后,您可以将其格式化为您想要的任何格式。如果您想要特定于语言环境的格式,只需使用:

DateTimeFormat.getFormat(PredefinedFormat.DATE_SHORT).format(date);

这是特定于语言环境的,因此输出可能会有所不同。在我的系统中,我有:

2017-03-27


Java新Date/TimeAPI

虽然您使用的是 GWT,但日期 parsing/formatting 的这个特定代码可以由更好的 API 处理。 GWT 使用 java.util.Date,它有 lots of problems and design issues.

如果您正在使用 Java 8,请考虑使用 new java.time API. It's easier, less bugged and less error-prone than the old APIs.

如果您使用 Java <= 7,您可以使用 ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it ).

下面的代码适用于两者。 唯一的区别是包名称(在 Java 8 中是 java.time,在 ThreeTen Backport(或 Android 的 ThreeTenABP)中是 org.threeten.bp),但是 classes和方法names是一样的。

要解析和格式化日期,您可以使用 DateTimeFormatter。由于您只使用日、月和年,我使用的是 LocalDate class(只有日期字段):

String input = "270317";
// parse the date
DateTimeFormatter parser = DateTimeFormatter.ofPattern("ddMMyy");
LocalDate date = LocalDate.parse(input, parser);

// locale specific format
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
System.out.println(formatter.format(date));

由于这是特定于区域设置的,在我的系统中我得到了输出:

27/03/17

如果您想使用与 GWT 生成的完全相同的模式,您可以使用:

// get the GWT format
String pattern = DateTimeFormat.getFormat(PredefinedFormat.DATE_SHORT).getPattern();
// use the same format in the formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
System.out.println(formatter.format(date));

基于 GWT docs,它似乎使用与 DateTimeFormatter 兼容的模式(至少对于日期字段),因此这应该适用于所有情况。

如果你想要一个固定的格式(比如03/27/2017),就这样做:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

查看 javadoc 了解有关日期模式的更多详细信息。