我使用的是 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);
这给了我这个异常(exception):
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)
有什么想法吗?
附注请注意:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy. HH:mm:ss");
DateTime dt = formatter.parseDateTime(string);
在 Java 8 中不起作用。
编辑:我的问题不够清楚,我的错:
我的 .txt
文件中有这个字符串,我需要将其转换为 LocalDateTime
对象,以便将其保存到类对象中,但我需要它按照规定的格式,以便将其打印在表格内。我不希望它以 "2017-10-06T17:48:23.558"
的原始格式打印出来。我希望它打印出这样的内容:“10.06.2017.17:48:23”
最佳答案
您想要的输出格式 ("dd.MM.yyyy.HH:mm:ss"
) 与输入不同,因此您无法使用它进行解析。
在此特定情况下,输入位于 ISO8601 format 中,所以你可以直接解析它。然后使用格式化程序将 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));
输出为:
<小时/>06.10.2017. 17:48:23
PS:如果输入采用不同的格式,您应该使用一种格式化程序进行解析,然后使用另一种格式化程序进行格式化。 Check the javadoc查看所有可用的格式。
关于java - 使用 Java 8 DateTimeFormatter 将字符串转换为 LocalDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46786585/