扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

simpledateformat如何转换为LocalDateTime

扬州沐宇科技
2024-06-19 14:05:03
simpledateformat

要将SimpleDateFormat转换为LocalDateTime,可以使用以下方法:

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

public class Main {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = "2022-09-30 12:00:00";

        try {
            LocalDateTime localDateTime = LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            System.out.println("Converted LocalDateTime: " + localDateTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,我们首先创建了一个SimpleDateFormat对象,并用一个日期字符串初始化它。然后,我们使用DateTimeFormatter将日期字符串转换为LocalDateTime对象。最后,我们打印出转换后的LocalDateTime。

扫码添加客服微信