我输入了许多不同格式的日期。我基本上试图采用所有不同的格式,并将它们标准化为ISO 8601格式。
如果日期包含月份名称,例如March,那么我使用以下函数来获取月份编号,例如03。
month = String.valueOf(Month.valueOf(month.toUpperCase()).getValue());
无论如何,我遇到的问题是月份名称有多种语言,没有任何语言表明它们会是什么语言。运行上述功能时出现以下错误:
Caused by: java.lang.IllegalArgumentException: No enum constant java.time.Month.AUGUSTI
at java.lang.Enum.valueOf(Enum.java:238)
at java.time.Month.valueOf(Month.java:106)
是否有任何图书馆可以处理多种语言的月份名称,返回数值,甚至只是将月份名称翻译成英文?
以下是输入日期的示例:
1370037600
1385852400
1356994800
2014-03-01T00:00:00
2013-06-01T00:00:00
2012-01-01
2012
May 2012
März 2010
Julio 2009
答案 0 :(得分:4)
如果您不知道月份名称是什么语言,唯一的方法是遍历java.util.Locale
的所有可用值,使用java.time.format.DateTimeFormatter
并尝试解析月份,直到找到一个有效的:
String input = "März 2010";
// formatter with month name and year
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MMMM yyyy");
Month month = null;
for (Locale loc : Locale.getAvailableLocales()) {
try {
// set the locale in the formatter and try to get the month
month = Month.from(fmt.withLocale(loc).parse(input));
break; // found, no need to parse in other locales
} catch (DateTimeParseException e) {
// can't parse, go to next locale
}
}
if (month != null) {
System.out.println(month.getValue()); // 3
}
在上面的代码中,月份为Month.MARCH
,输出为3
。