我尝试将字符串转换为LocalDateTime。这是我的代码

String val = "2015-07-18T13:32:56.971-0400"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
java.time.LocalDateTime dateTime = java.time.LocalDateTime.parse(val, formatter);


但是这样做时出现以下错误

The method ofPattern(String) is undefined for the type DateTimeFormatter
The method parse(CharSequence, DateTimeFormatter) in the type LocalDateTime is not applicable for the arguments (String, DateTimeFormatter)


有人可以建议我做什么

最佳答案

您的代码大部分是正确的。首先,请确保您导入了正确的软件包:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


其次,您的第一行在String val的第一个字符中有一个错字(-),并且缺少分号:

// Remove - from the String and put ; at the end
// String val = "-2015-07-18T13:32:56.971-0400"
String val = "2015-07-18T13:32:56.971-0400";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
LocalDateTime dateTime = java.time.LocalDateTime.parse(val, formatter);
//Print to test:
System.out.println(dateTime);
//Result on the console: 2015-07-18T13:32:56.971

关于java - 将String转换为java.sql.LocalDateTime时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60299422/

10-11 19:38