我尝试将字符串转换为 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;
其次,您的第一行字符串 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/