localdateTime转date及LocalDateTime格式化转换字符串

localdateTime转date及LocalDateTime格式化转换字符串

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
 
public class LocalDateTimeToDate {
    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.now(); // 获取当前时间
        ZoneId zoneId = ZoneId.systemDefault(); // 获取系统默认时区
        ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId); // 将 LocalDateTime 转换为 ZonedDateTime
        Date date = Date.from(zonedDateTime.toInstant()); // 将 ZonedDateTime 的 Instant 转换为 Date
        System.out.println(date); // 打印 Date 对象
    }
}

如果你需要格式化你的LocalDateTime(例如:转换为字符串),你可以使用DateTimeFormatter。例如:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:MM:SS");
String formatted = localDateTime.format(formatter);

 

posted on 2025-05-28 09:49  oktokeep  阅读(407)  评论(0)    收藏  举报