package org.jeecg.common.util;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
/**
* @Description:Date 和 LocalDateTime 的工具类
* @CreateDate:15:59 2023/3/13
*/
public class LocalDateTimeUtils {
/**
* Date 转 LocalDateTime
* @param date 参数为 Date
* @return 返回为:LocalDateTime
*/
public static LocalDateTime dateToLocalDateTime(Date date){
//1.从日期获取ZonedDateTime并使用其方法toLocalDateTime()获取LocalDateTime
//2.使用LocalDateTime的Instant()工厂方法
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime endLocal = date.toInstant().atZone(zoneId).toLocalDateTime();
//LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), zoneId);
return endLocal;
}
/**
* LocalDateTime 转 Date
* @param loTime 参数为 LocalDateTime
* @return 返回为 Date
*/
public static Date localDateTimeToDate(LocalDateTime loTime) {
//1.使用atZone()方法将LocalDateTime转换为ZonedDateTime
//2.将ZonedDateTime转换为Instant,并从中获取Date
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = loTime.atZone(zoneId);
Date date = Date.from(zdt.toInstant());
return date;
}
public static void main(String[] args) throws Exception {
//yyyy-MM-dd HH:mm:ss
//LocalDateTime loTime = LocalDateTime.now();
//long minutes = duration.toMinutes();//两个时间差的分钟数
//long hours = duration.toHours();//小时
//DayOfWeek dayOfWeek = loTime.getDayOfWeek();
//int value = dayOfWeek.getValue();
/*Date d=new Date();
Long s=d.getTime();
System.out.println(s.toString().getBytes("UTF-8").length);*/
//方法一:中文操作系统中打印GBK
//System.out.println(System.getProperty("file.encoding"));
//方法二:中文操作系统中打印GBK
//System.out.println(Charset.defaultCharset());
}
}
LocalDateTimeUtils保存:时间的toInstant().atZone(zoneId) 和 Date.from参数为:loTime.atZone(zoneId).toInstant()
![](https://img-home.csdnimg.cn/images/20240711042549.png)