1

当我尝试将此字符串转换为日期时出现错误:

String s = "Mon, 11-12-2021 - 12:00";
LocalDateTime localDateTime = LocalDateTime.parse(s, DateTimeFormatter.ofPattern("EEE, MM-dd-yyyy - HH:mm"));

我懂了:

  Exception in thread "main" java.time.format.DateTimeParseException: Text 'Mon, 11-12-2021 - 12:00' could not be parsed at index 0

    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at Main.main(Main.java:11)

是否可以在 Java 中转换此字符串,或者应该以某种方式对其进行更改?

4

4 回答 4

4

也许您的语言环境不是英语。然后你需要传递Locale.ENGLISH给你的 DateTimeFormatter。

这对我有用,连同@Narcis Postolache 的日期更改为Fri.

String s = "Fri, 11-12-2021 - 12:00";
LocalDateTime localDateTime = LocalDateTime.parse(s, DateTimeFormatter.ofPattern("EEE, MM-dd-yyyy - HH:mm", Locale.ENGLISH));

localDateTime 对象:2021-11-12T12:00

于 2021-11-16T09:11:25.140 回答
0

对于您请求的模式,根据官方文档指定不同的预定义格式化程序可能是个好主意(看看不同的选项)

String pattern = "Mon, 11 Dec 2021 12:00:00 GMT";
LocalDate formatter = LocalDate.parse(pattern, DateTimeFormatter.RFC_1123_DATE_TIME);

此外,如果您不想转换月份,您可以执行以下操作:

LocalDateTime local = LocalDateTime.parse("2021-12-11T12:00:00");

然后通过以下方式获取星期几:

System.out.println(local.getDayOfWeek());
于 2021-11-16T09:24:47.770 回答
0

试试
String s = "Fri, 11-12-2021 - 12:00";

于 2021-11-16T08:59:14.380 回答
0

您的默认语言环境不是美国,2021 年 11 月 12 日不是星期一而是星期五:

String s = "Fri, 11-15-2021 - 12:00";
LocalDateTime localDateTime = LocalDateTime.parse(s, 
          DateTimeFormatter.ofPattern("EEE, MM-dd-yyyy - HH:mm", Locale.US));
于 2021-11-16T09:14:38.160 回答