一、Date与LocalDate、LocalTime、LocalDateTime互转
1.Date转LocalDate、LocalTime、LocalDateTime
Date date = new Date();Instant instant = date.toInstant();Instant now = Instant.now(); //Instant.now()与new Date().toInstant()的结果一样,时间戳ZoneId zoneId = ZoneId.systemDefault(); //时区,zoneId = Asia/ShanghaiZonedDateTime zonedDateTime = instant.atZone(zoneId);LocalDate localDate = zonedDateTime.toLocalDate();LocalTime localTime = zonedDateTime.toLocalTime();LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
或者
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);LocalDate localDate = localDateTime.toLocalDate();LocalTime localTime = localDateTime.toLocalTime();
组成工具方法:
public LocalDateTime getLocalDateTime(Date date) {return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();}
或者
public LocalDateTime getLocalDateTime(Date date) {return LocalDateTime.of(date.getYear(), date.getMonth(), date.getDay(), date.getHours(), date.getMinutes(), date.getSeconds());}
date的以上get方法已过期,不建议使用
2.LocalDate、LocalTime、LocalDateTime转Date
LocalDateTime now = LocalDateTime.now();ZoneId zoneId = ZoneId.systemDefault();LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now(), LocalTime.now());Instant instant = now.atZone(zoneId).toInstant();Date date = Date.from(instant);
二、LocalDate常用方法
1.获取当月第一天和最后一天
LocalDate now = LocalDate.now();LocalDate firstDay = now.with(TemporalAdjusters.firstDayOfMonth()); //当月第一天LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth()); //当月最后一天
2.日期加减
minusXXX:减
plusXXX:加
3.日期比较
相等:isEqual
int compareTo0(LocalDate otherDate) {int cmp = (year - otherDate.year);if (cmp == 0) {cmp = (month - otherDate.month);if (cmp == 0) {cmp = (day - otherDate.day);}}return cmp;}
大于:isAfter
小于:isBefore
4.分别获取年月日
int year = now.getYear();int monthValue = now.getMonthValue();int dayOfMonth = now.getDayOfMonth();
5.两个日期相差多少
使用Period的静态方法between
public static Period between(LocalDate startDateInclusive, LocalDate endDateExclusive) {return startDateInclusive.until(endDateExclusive);}
返回值是一个Period对象,可以用getXXX方法获取对应的数字,如getMonths
从源码可以看出来实际调用的还是LocalDate的until方法
LocalDate有两个until方法:
①public Period until(ChronoLocalDate endDateExclusive)
②public long until(Temporal endExclusive, TemporalUnit unit)
以上两个方法都是参数-方法调用者,第一个方法将结果组装成Period对象,可以用getXXX方法获取对应的数字,如getMonths;第二个方法有一个参数unit,它表示将结果转换成什么,如ChronoUnit.DAYS是将结果转换成天。
ChronoUnit是TemporalUnit 的实现类。
6.修改日期
withXXX:将对应的位置修改为指定的数字
例:
将当前年修改为,月修改为2,其他不变:LocalDate.now().withMonth(2).withYear()
7.当前月、年有多少天
LocalDate now = LocalDate.now();int day = now.lengthOfMonth(); //本月有多少天int month = now.lengthOfYear(); //今年有多少天
源码:
public int lengthOfMonth() {switch (month) {case 2:return (isLeapYear() ? 29 : 28);case 4:case 6:case 9:case 11:return 30;default:return 31;}}
public int lengthOfYear() {return (isLeapYear() ? 366 : 365);}
public boolean isLeapYear(long prolepticYear) {return ((prolepticYear & 3) == 0) && ((prolepticYear % 100) != 0 || (prolepticYear % 400) == 0);}
三、LocalTime、LocalDateTime常用方法与以上类似
四、Instant
计算机存储的当前时间,本质上是一个不断递增的整数。Java提供的System.currentTimeMillis()返回的就是以毫秒表示的当前时间戳。这个时间戳在java.time中以Instant类型表示,我们用Instant.now()获取当前时间戳,效果System.currentTimeMillis()类似。
//当前时间戳是多少秒System.out.println(Instant.now().getEpochSecond());//毫秒System.out.println(Instant.now().toEpochMilli());
public final class Instantimplements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable {private final long seconds; private final int nanos;}
Instant
类只有两个属性,一个秒,一个更精确的纳秒。
既然Instant
就是时间戳,那么,给它附加上一个时区,就可以创建出ZonedDateTime
:
Instant now = Instant.now(); //Instant.now()与new Date().toInstant()的结果一样,时间戳ZoneId zoneId = ZoneId.systemDefault(); //时区,zoneId = Asia/ShanghaiZonedDateTime zonedDateTime = instant.atZone(zoneId);
五、常用写法
with
方法用来对时间和日期进行调整。
public LocalDate with(TemporalAdjuster adjuster)
通过传入一个调整器对时间调整。
日期校正器 TemporalAdjuster
每个月第一天和最后一天:
//月第一天LocalDate first = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());//月最后一天LocalDate last = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
当前日期所在周的周一:
//周一LocalDate.now().with(WeekFields.ISO.getFirstDayOfWeek());//周一,要周几第二个数字就是几,从1-7LocalDate.now().with(WeekFields.ISO.dayOfWeek(),1L);
格式化:
TemporalAccessor yyyyMM = DateTimeFormatter.ofPattern("yyyyMM").parse("02");LocalDate of = LocalDate.of(yyyyMM.get(ChronoField.YEAR), yyyyMM.get(ChronoField.MONTH_OF_YEAR),1);System.out.println(of); //-02-01//LocalDateLocalDate localDate = LocalDate.of(, 2, 2);String format = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));LocalDate parse = LocalDate.parse("-06-06", DateTimeFormatter.ofPattern("yyyy-MM-dd"));//LocalDateTimeLocalDateTime localDateTime = LocalDateTime.of(localDate, LocalTime.of(10, 10, 10));String format1 = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));LocalDateTime parse1 = localDateTime.parse("-06-06 10:10:10", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
六、Period
Period类用来度量两个日期之间年、月、日的间隔值,即两个日期隔了多少个年、月、日。
如果是指定某年,某月,某日相差总数,请使用LocalDate的until
方法。
七、Duration
Duration类用来度量秒或纳秒时间间隔,适合处理较短的时间,需要更高的精确性。
八、DateTimeFormatter
适用于parse
方法。时间格式化。