Fra*_*fka 4 java datetime translation date-parsing java-time
我输入了许多不同格式的日期。我基本上是在尝试采用所有不同的格式并将它们标准化为 ISO 8601 格式。
如果日期包含月份名称,例如三月,那么我将使用以下函数来获取月份编号,例如 03。
month = String.valueOf(Month.valueOf(month.toUpperCase()).getValue());
Run Code Online (Sandbox Code Playgroud)
无论如何,我遇到的问题是月份名称有许多不同的语言,没有说明它们将是什么语言。运行上述函数时出现以下错误:
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)
Run Code Online (Sandbox Code Playgroud)
是否有任何库可以处理多种不同语言的月份名称,返回数值,甚至只是将月份名称翻译成英文?
这是输入日期的示例:
1370037600
1385852400
1356994800
2014-03-01T00:00:00
2013-06-01T00:00:00
2012-01-01
2012
May 2012
März 2010
Julio 2009
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您不知道月份名称是什么语言,唯一的方法是遍历 的所有可用值java.util.Locale,使用 ajava.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
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,月份是Month.MARCH,输出是3。
| 归档时间: |
|
| 查看次数: |
1241 次 |
| 最近记录: |