import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* 时间、日期转换工具类
*/
public class TimeTransferUtil {
// 默认时区
protected static final ZoneId zone = ZoneId.systemDefault();
/**
* 日期 to LocalDate
*/
public static LocalDate dateToLocalDate(Date date) {
return date.toInstant().atZone(zone).toLocalDate();
}
/**
* LocalDate to 日期
*/
public static Date localDateToDate(LocalDate localDate) {
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
return Date.from(instant);
}
/**
* 日期 to LocalDateTime
*/
public static LocalDateTime dateToLocalDateTime(Date date) {
return date.toInstant().atZone(zone).toLocalDateTime();
}
/**
* LocalDateTime to 日期
*/
public static Date localDateTimeToDate(LocalDateTime dateTime) {
Instant instant = dateTime.atZone(zone).toInstant();
return Date.from(instant);
}
/**
* 时间戳 to LocalDateTime
*/
public static LocalDateTime millisToLocalDataTime(long millis) {
return Instant.ofEpochMilli(millis).atZone(zone).toLocalDateTime();
}
/**
* 时间戳 to LocalDateTime 2
*/
public LocalDateTime millisToLocalDataTime2(long timestamp){
Instant instant = Instant.ofEpochMilli(timestamp);
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
/**
* LocalDateTime to 时间戳
*/
public static long localDateTimeToMillis(LocalDateTime dateTime) {
return dateTime.atZone(zone).toInstant().toEpochMilli();
}
/**
* 相差天数
*/
public static long getOffsetDays(LocalDate from, LocalDate to) {
return to.toEpochDay() - from.toEpochDay();
}
/**
* 相差月数
*
* 或者使用
* from.until(to, ChronoUnit.DAYS))
* from.until(to, ChronoUnit.WEEKS)
* from.until(to, ChronoUnit.MONTHS)
*/
public static long getOffsetMonths(LocalDate from, LocalDate to) {
return (to.getYear() - from.getYear()) * 12L + (to.getMonthValue() - from.getMonthValue());
}
}
java8 Date与LocalDataTiem工具类
于 2022-08-10 11:01:16 首次发布