Java DateTimeFormatter和LocalDateTime.解析问题



很抱歉这个问题是基本的,并且无法显示我已经尝试过的事情。但是到目前为止,我很难理解java的DateTimeFormatter和LocalDateTime。

不工作的代码,但显然在我不知道的一些变化之前一直在工作(我刚刚得到了这段代码):

public getDateForIception() {
String tid = driver.findElement(By.cssSelector("div.hendelse-tid.hb-tekst--ingenBryting"))
.getText().replaceAll("(?<=[A-Za-z]{3})[.a-z]{1,2}", "");
if(tid.split("\.")[0].length() == 1) {
tid = "0" + tid;
}
return DatoUtils.parseDatoLocalDateTime(tid,  "dd. MMM yyyy HH:mm");
}

不完全确定替换字符等的意义是什么,但在这种情况下,if()没有执行,而"变量不变。我把它保存在这里以备参考。

public static LocalDateTime parseDatoLocalDateTime(String datoString, String pattern) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern(pattern)
.toFormatter(Locale.forLanguageTag("no"));
return LocalDateTime.parse(datoString, formatter);
}

我怀疑从页面读取的格式发生了一些变化,因此解析失败。但是错误信息对我来说意义不大:

java.time.format.DateTimeParseException: Text '15. jun 2022 19:51' could not be parsed at index 4

非常感谢您的想法或解决方案。

在格式化器构建器中,挪威语是由这一行

设置的
.toFormatter(Locale.forLanguageTag("no"));

您可以通过使用语言标记en将区域设置为英语,或者您应该提供挪威月份名称(末尾有一个点表示缩短的变体),如jan.,feb.,mar.,apr.,mai(点是不需要的,因为它是一个完整的月份名称),等等。


编辑:经过进一步的研究,我发现您可以解析挪威月份,而不需要在末尾添加一个额外的点。要做到这一点,您需要使用一个月的独立格式(ll而不是MMM)。

那么,你的代码就是这样的

public getDateForIception() {
String tid = driver.findElement(By.cssSelector("div.hendelse-tid.hb-tekst--ingenBryting"))
.getText().replaceAll("(?<=[A-Za-z]{3})[.a-z]{1,2}", "");
if(tid.split("\.")[0].length() == 1) {
tid = "0" + tid;
}
return DatoUtils.parseDatoLocalDateTime(tid,  "dd. LLL yyyy HH:mm");
}
public static LocalDateTime parseDatoLocalDateTime(String datoString, String pattern) {
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern(pattern)
.toFormatter(Locale.forLanguageTag("no"));
return LocalDateTime.parse(datoString, formatter);
}

最新更新