Java中时间相关方法
代码环境:
java version “11.0.14” 2022-01-18 LTS
IntelliJ IDEA 2020.3 (Ultimate Edition)
Windows 10 企业版 LTSC 21H2 19044.1706
时间类的相关转化
Date类
/**
* date 转 LocalDateTime
* @param date
* @return
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
if( date == null ){
return null;
}
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}
/**
* date 转 Calendar
* @param date
* @return
*/
public static Calendar dateToCalendar(Date date){
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
Calendar类
/**
* Calendar 转 LocalDateTime
* @param calendar
* @return
*/
public static LocalDateTime calenderToLocalDateTime(Calendar calendar){
if (calendar == null) {
return null;
}
return LocalDateTime.ofInstant(calendar.toInstant(), ZoneOffset.systemDefault());
}
/**
* Calendar 转 date
* @param calendar
* @return
*/
public static Date calenderToDate(Calendar calendar){
if (calendar == null) {
return null;
}
return new Date(calendar.getTimeInMillis());
}
LocalDateTime类
/**
* LocalDateTime 转 date
* @param localDateTime
* @return
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
if (localDateTime == null) {
return null;
}
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
/**
* LocalDateTime 转 Calendar
* @param localDateTime
* @return
*/
public static Calendar localDateTimeToCalender(LocalDateTime localDateTime){
if (localDateTime == null) {
return null;
}
return GregorianCalendar.from(ZonedDateTime.of(localDateTime, ZoneId.systemDefault()));
}
这里均是转化成开发中常用的格式 yyyy-MM-dd HH:mm:ss
,实现三大类之间的转换
这里用自己写的工具类来说明
package com.ptool