public class DateAndTime {
/**
* Date 输出一个标准时间,可读性差
* LocalDate 年月日
* LocalTime 时分秒
* LocalDateTime 年月日时分秒
*
* Instant 与日期对象在时间线上相同点的实例
* ZoneId/ZoneOffset 时区
* ZoneId表示一个时区实例,他的内部定义了一个地区的时区规则集,ZoneId.systemDefault()获取系统默认时区
* ZoneOffSet表示与UTC时间的偏移时间,格式为+08:00、-04:00
*
* LocalDate,LocalTime转LocalDateTime,都可以通过对应的atTime()方法
* localTime.atDate(localDate)
* localDate.atTime(localTime);
*/
public static void main(String[] args) {
Date date = new Date();
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
}
/**
* 将 Date 转换成LocalDate
*/
public static LocalDate dateToLocalDate(Date date){
/* Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
return instant.atZone(zoneId).toLocalDate();*/
return LocalDate.from(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
}
/**
* 将 Date 转换成LocalDateTime
*/
public static LocalDateTime dateToLocalDateTime(Date date){
/* Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
return instant.atZone(zoneId).toLocalDateTime();*/
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
/**
* 将LocalDate转换成Date
*/
public static Date localDateToDate(LocalDate localDate){
/* ZoneId zone = ZoneId.systemDefault();
Instant instant = localDate.atStartOfDay().atZone(zone).toInstant();
return Date.from(instant);*/
return Date.from(localDate.atStartOfDay().atZone(ZoneOffset.of("+8")).toInstant());
}
/**
* LocalDateTime转换成Date
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime){
/* ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
Instant instant = zonedDateTime.toInstant();
return Date.from(instant);*/
return Date.from(localDateTime.atZone(ZoneOffset.of("+8")).toInstant());
}
}
已经有Date为什么要用LocalDate
LocalDate、LocalTime、LocalDateTime都是java8新提供的类;
Date直接打印可读性差,需要使用SimpleDateFormat格式化,但是SimpleDateFormat是非线程安全的
具体可参考:
使用LocalDateTime而不是Date