java - 将 String 转换为 java.sql.LocalDateTime 时出错

标签 java

我尝试将字符串转换为 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/

相关文章:

java - 当两个接口(interface)有冲突的返回类型时,为什么一个方法成为默认方法?

java - JNI 和 Android...UnsatisfiedLinkError

java - 阻止 ArrayOutOfBoundsException 在 Java 中停止程序执行

java - "java web start"有什么用?

java - 如何使用字符串作为输入创建并输出日期对象?即 "13/04/1998"

java - 是否可以编写跨数据库连接查询?

java - Servet - 为什么我会收到空​​指针异常?

java - 使用POI用java替换word模板文档中的内容

java - 任何人都可以帮助解决这个 Stack/List 问题吗?

java - 堆外数组的直接操作