JAVA Date与LocalDateTime互转

public class test{
    public static void main(String[] arg){
        //Date转为LocalDateTime
        DateTimeFormatter sdf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Date nowDate = new Date();
        LocalDateTime nowL = Instant.ofEpochMilli(nowDate.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
        //或LocalDateTime nowL = nowDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
        System.out.println(sdf1.format(nowL));


        //LocalDateTime转为Date
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        Date nowD = Date.from(nowLocalDateTime.atZone(ZoneId.systemDefault()).toInstant());
        System.out.println(sdf2.format(nowD));

    }


}

 

posted @ 2021-06-03 17:13  哎丫丫呀喂  阅读(299)  评论(0编辑  收藏  举报