上篇文章介绍了Java8和Java8之前的时间处理的相关类,但是在日常开发中难免会遇到Java8和之前的旧对象互转的需求。我整理了一下之前的内容,做了一个工具类,如下:
public class DateUtils {
/**
* @Author: zhuoli
* @Description: 判断unix当前unix时间是否为0点
* @param unixTimeStamp
* @Date: 上午12:06 2018/6/15
*/
public static Boolean at0Clock(Long unixTimeStamp){
return (unixTimeStamp + 8 * 3600) % 86400 == 0;
}
/**
* @Author: zhuoli
* @Description: Date -> LocalDateTime
* @param date
* @Date: 上午12:05 2018/6/15
*/
public static LocalDateTime getLocalDateTimeFormDate(Date date){
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone);
}
/**
* @Author: zhuoli
* @Description: Date -> LocalDate
* @param date
* @Date: 上午12:05 2018/6/15
*/
public static LocalDate getLocalDateFromDate(Date date){
LocalDateTime localDateTime = getLocalDateTimeFormDate(date);
return localDateTime.toLocalDate();
}
/**
* @Author: zhuoli
* @Description: Date -> LocalTime
* @param date
* @Date: 上午12:05 2018/6/15
*/
public static LocalTime getLocalTimeFromDate(Date date){
LocalDateTime localDateTime = getLocalDateTimeFormDate(date);
return localDateTime.toLocalTime();
}
/**
* @Author: zhuoli
* @Description: LocalDateTime -> Date
* @param localDateTime
* @Date: 上午12:17 2018/6/15
*/
public static Date getDateFromLocalDateTime(LocalDateTime localDateTime){
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return Date.from(instant);
}
/**
* @Author: zhuoli
* @Description: LocalDate -> Date,时间为00:00:00
* @param localDate
* @Date: 上午12:16 2018/6/15
*/
public static Date getDateFromLocalDate(LocalDate localDate){
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
return Date.from(instant);
}
/**
* @Author: zhuoli
* @Description: 把当天的LocalTime转化为Date
* @param localTime
* @Date: 上午12:15 2018/6/15
*/
public static Date getDateFromLocalTime(LocalTime localTime){
LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
ZoneId zone = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zone).toInstant();
return Date.from(instant);
}
}
代码放在上篇文章的测试代码相同的位置码云 – 卓立 – java8时间类