LocalDateTime、LocalDate是JDK1.8提供的新的时间操作接口,而Date是JDK1.0提供的时间操作接口,LocalDateTime/LocalDate提供许多便捷的时间操作函数,使用起来相当方便,在实际的编程中经常会用到这几个类,有时候难免会存在相互转换的情况,本文将使用代码讲解具体的转换过程。
一、LocalDateTime转Date
package com.test;
import java.time.ZoneId;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Calendar;
public class Test{
public static void main(String[] args)
// LocalDateTime 转 Date
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("local:"+localDateTime.getYear());
ZoneId zoneId = ZoneId.systemDefault();
Date date = Date.from(localDateTime.atZone(zoneId).toInstant());
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println("date:"+calendar.get(Calendar.YEAR));
}
二、LocalDate转Date
package com.test;
import java.time.ZoneId;
import java.time.LocalDate;
import java.util.Date;
import java.util.Calendar;
public class Test{
public static void main(String[] args)
// LocalDate 转 Date
LocalDate localDate = LocalDate.now();
System.out.println("local:"+localDate.getYear());
ZoneId zoneId = ZoneId.systemDefault();
Date date = Date.from(localDate.atStartOfDay().atZone(zoneId).toInstant());
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println("date:"+calendar.get(Calendar.YEAR));
}
三、Date转LocalDate、LocalDateTime
package com.test;
import java.time.ZoneId;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Calendar;
public class Test{
public static void main(String[] args){
Date date = new Date();
// Date 转 LocalDate
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
LocalDate localDate = LocalDate.of(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(DAY_OF_MONTH));
// Date 转 LocalDateTime
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(),ZoneId.systemDefault());
}
}