java.time.LocalDateTime和java.util.Date互相转化

我们来看一下java.time.LocalDateTime和java.util.Date互相转化的方法。

public static void main(String[] args) {
        //LocalDateTime to Date
        LocalDateTime ldtToDate = LocalDateTime.now();
        DateTimeFormatter formatterStart = DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00");
        //获取开始时间
        System.out.println(formatterStart.format(ldtToDate));

        //转换LocalDateTime to Date
        System.out.println("默认时区:"+ ZoneId.systemDefault());
        Date d = Date.from(ldtToDate.atZone(ZoneId.systemDefault()).toInstant());
        System.out.println(d);

        //转换Date to LocalDateTime
        Date date = new Date();
        ZonedDateTime dateToLDT = date.toInstant().atZone(ZoneId.systemDefault());
        LocalDateTime ldt = dateToLDT.toLocalDateTime();
        System.out.println(ldt);

    }