我有以下方法,它获取一个日期字符串,并尝试将其格式化为LocalDateTime对象:
(当地语言为挪威语)
public static LocalDateTime parseDatoLocalDateTime2(String datoString, String pattern, String language) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern(pattern)
.toFormatter(Locale.forLanguageTag(language));
return LocalDateTime.parse(datoString, formatter);
}
据我所知,这些是正确的“格式代码”:
yyyy = 2024
yy = 24
MMMM = April
MMM = Apr
MM = 04
dd = 09
d = 9
因此,这是有效的:
String testdato1 = "8. 04. 2024 15:32";
parseDatoLocalDateTime2(testdato1, "d. MM. yyyy HH:mm", "no");
String testdato2 = "8. april 2024 15:32";
parseDatoLocalDateTime2(testdato2, "d. MMMM yyyy HH:mm", "no");
为什么这不起作用?
String testdato3 = "8. apr 2024 15:32";
parseDatoLocalDateTime2(testdato3, "d. MMM yyyy HH:mm", "no");
此操作失败
java.time.format.DateTimeParseException: Text '8. apr 2024 15:32' could not be parsed at index 3
但为什么呢?据我所知,“MMM”是月份的简称(“apr”、“jul”等)。
我甚至说“基本”或“白痴”,问ChatGTP:
Me: Can you show me how to use Java DateTimeFormatter to parse this string into a LocalDateTime object with Norwegian locale: "8. apr. 2024 15:32"
ChatGTP:
String dateString = "8. apr. 2024 15:32";
// Define the formatter pattern with Norwegian locale
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d. MMM. yyyy HH:mm", new Locale("no"));
// Parse the string into a LocalDateTime object
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
// Print the parsed LocalDateTime object
System.out.println(dateTime);
甚至这个代码也不适用于我。它或多或少以同样的方式失败:
Text '8. apr. 2024 15:32' could not be parsed at index 7