另一种方法是使用java.text.DateFormat:
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.ENGLISH);
日期和时间样式(第一个和第二个参数)可以是SHORT、MEDIUM、LONG 或FULL。如果需要,您可以使用Locale.getDefault() 获取设备的默认语言。
我不确定哪种样式组合可以满足您的需求 - 它们都给了我不同的输出,没有一个给我您描述的那个。
这是因为 JVM 中嵌入了特定于语言环境的格式,我不确定它在不同的 API 级别和设备之间有何不同。
如果上面的解决方案有效,那就没问题了。否则,另一种方法是为每个区域设置特定的模式:
// get device's locale
Locale locale = Locale.getDefault();
String pattern = "";
// check language
if ("en".equals(locale.getLanguage())) {
// english
pattern = "dd MMMM yyyy, h.mm a";
} else if ("de".equals(locale.getLanguage())) {
// german
pattern = "dd.MM.yyyy, HH:mm 'Uhr'";
} else {
pattern = // use some default pattern for other languages?
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
String formattedDate = sdf.format(new Date());
一个细节是,在我的 JVM 中,英语语言环境的 AM/PM 符号是大写的,因此您可能需要通过以下方式进行调整:
// change AM/PM to am/pm (only for English)
if ("en".equals(locale.getLanguage())) {
formattedDate = formattedDate.toLowerCase();
}
java.time API
在 API 级别 26 中,您可以使用 java.time API。对于较低级别,有一个 nice backport,具有相同的类和功能。
这更好用。代码可能看起来相似,但类本身解决了lots of internal issues of the old API。
您可以先尝试获取 JVM 的本地化模式,看看它们是否与您的输出匹配:
Locale locale = Locale.getDefault();
FormatStyle style = FormatStyle.MEDIUM;
String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(style, style, IsoChronology.INSTANCE, locale);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern, locale);
或者同上:
// get device's locale
Locale locale = Locale.getDefault();
String pattern = "";
// check language
if ("en".equals(locale.getLanguage())) {
// english
pattern = "dd MMMM yyyy, h.mm a";
} else if ("de".equals(locale.getLanguage())) {
// german
pattern = "dd.MM.yyyy, HH:mm 'Uhr'";
} else {
pattern = ""; // use some default pattern?
}
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern, locale);
String formattedDate = LocalDateTime.now().format(fmt);
在我的测试中,我遇到了英语大写 AM/PM 的同样问题。您可以通过调用toLowerCase() 来解决此问题,但此 API 还允许您创建更灵活的格式化程序。
并且格式化程序是线程安全的(而SimpleDateFormat 不是),因此您可以根据语言创建格式化程序的静态映射,并根据需要多次重复使用它们:
// map of formatters
Map<String, DateTimeFormatter> formatterMap = new HashMap<>();
// English formatter
Map<Long, String> customAmPmSymbols = new HashMap<>();
customAmPmSymbols.put(0L, "am");
customAmPmSymbols.put(1L, "pm");
DateTimeFormatter f = new DateTimeFormatterBuilder()
// date/time
.appendPattern("dd MMMM yyyy, h.mm ")
// custom AM/PM symbols (lowercase)
.appendText(ChronoField.AMPM_OF_DAY, customAmPmSymbols)
// create formatter
.toFormatter(Locale.ENGLISH);
// add to map
formatterMap.put("en", f);
// German formatter
formatterMap.put("de", DateTimeFormatter.ofPattern("dd.MM.yyyy, HH:mm 'Uhr'", Locale.GERMAN));
// get device's locale
Locale locale = Locale.getDefault();
DateTimeFormatter fmt = formatterMap.get(locale.getLanguage());
if (fmt != null) {
String formattedDate = LocalDateTime.now().format(fmt);
}