使用 Java 8 DateTimeFormatter 将字符串转换为 LocalDateTime

mde*_*nci 0 java datetime datetime-format datetime-parsing java-time

我正在使用 Java 8,我的.txt文件中有一个字符串,我想将其转换为LocalDateTime对象。

String time1 = "2017-10-06T17:48:23.558";

DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss");
LocalDateTime alarmTime = LocalDateTime.parse(time1, formatter1);

System.out.println(time1);
Run Code Online (Sandbox Code Playgroud)

这给了我这个例外:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2017-10-06T17:48:23.558' could not be parsed at index 2
at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDateTime.parse(Unknown Source)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

PS注意这个:

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy. HH:mm:ss");
DateTime dt = formatter.parseDateTime(string);
Run Code Online (Sandbox Code Playgroud)

在 Java 8 中不起作用。

编辑:我没有把问题说清楚,我的错:

我的.txt文件中有这个字符串,我需要将它转换为LocalDateTime对象以便将它保存到一个类对象中,但我需要按照规定的格式将它打印出来,以便在表格中打印出来。我不希望它以原始格式打印出来"2017-10-06T17:48:23.558"。我希望它打印出这样的东西:"10.06.2017. 17:48:23"

小智 5

您想要的输出 ( "dd.MM.yyyy. HH:mm:ss")格式与输入的格式不同,因此您无法使用它进行解析。

在这种特定情况下,输入采用ISO8601 格式,因此您可以直接解析它。然后您使用格式化程序将LocalDateTime对象格式化为您想要的格式:

String time1 = "2017-10-06T17:48:23.558";
// convert String to LocalDateTime
LocalDateTime localDateTime = LocalDateTime.parse(time1);
// parse it to a specified format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss");
System.out.println(localDateTime.format(formatter));
Run Code Online (Sandbox Code Playgroud)

输出是:

06.10.2017。17:48:23


PS:如果输入的格式不同,您应该使用一个格式化程序进行解析,并使用另一个格式化程序进行格式化。检查 javadoc以查看所有可用格式。