gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:20:34 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com