LocalDateTime、LocalDate是JDK1.8提供的新的时间操作接口,而Date是JDK1.0提供的时间操作接口,LocalDateTime/LocalDate提供许多便捷的时间操作函数,使用起来相当方便,在实际的编程中经常会用到这几个类,有时候难免会存在相互转换的情况,本文将使用代码讲解具体的转换过程。文章来源地址https://www.toymoban.com/news/detail-511265.html
一、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());
}
}
文章来源:https://www.toymoban.com/news/detail-511265.html
到了这里,关于LocalDateTime、LocalDate与Date互转的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!