Date与LocalDateTime互转

169 阅读1分钟

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)); } }