java8日期和时间的api在java.time包下
java8所有的日期和时间的api都是不可变类以及确保线程安全
基本使用
public static void main(String[] args) {
LocalDate localDate = LocalDate.now();
System.out.println(localDate);
System.out.println(
//2022
"year:"+localDate.getYear()+
//MAY
",month:"+ localDate.getMonth()+
//5
",monthValue:"+localDate.getMonthValue()+
//CE
",Era:"+localDate.getEra()+
//8
",DayOfMonth:"+localDate.getDayOfMonth()+
//SUNDAY
",DayOfWeek:"+localDate.getDayOfWeek()+
//128
",DayOfYear:"+localDate.getDayOfYear());
//2022-05-08
LocalDate localDate1 = LocalDate.of(2022, 5, 8);
System.out.println(localDate1);
//只关注月份+天数(例如每年的生日)
MonthDay monthDay = MonthDay.of(5, 8);
MonthDay monthDay1 = MonthDay.from(localDate1);
//true
System.out.println(monthDay.equals(monthDay1));
//关注时分秒13:16:36.373
LocalTime localTime = LocalTime.now();
System.out.println(localTime);
//增加三小时20分钟 16:36:36.373
LocalTime localTime1 = localTime.plusHours(3).plusMinutes(20);
System.out.println(localTime1);
//指定增加的数字和单位,注意:LocalDate没有时分秒,单位不可以是时分秒
LocalDate localDate2 = localDate.plus(1, ChronoUnit.DAYS);
System.out.println(localDate2);
//localdata1:2022-05-08 localDate2:2022-05-09
//判断localdata1是否在localDate2之后 false
System.out.println(localDate1.isAfter(localDate2));
//判断localdata1是否在localDate2之前 true
System.out.println(localDate1.isBefore(localDate2));
//判断localdata1是否和localDate2相等 false
System.out.println(localDate1.isEqual(localDate2));
// America/La_Paz, Antarctica/DumontDUrville, Asia/Taipei, Antarctica/South_Pole, Asia/Manila,
// Asia/Bangkok, Africa/Dar_es_Salaam, Poland, Atlantic/Madeira, Antarctica/Palmer, America/Thunder_Bay,
//......
Set<String> zoneIds = ZoneId.getAvailableZoneIds();
//转为treeset使之有序
Set<String>treesets = new TreeSet<String>(){
{
addAll(zoneIds);
}
};
System.out.println(zoneIds);
}
判断起止时间不能超过12个月
//计算起止时间不能超过12个月
public static boolean computeTimeDiff01(long startTimeMillis, long endTimeMillis){
//将startTimeMillis转为LocalDateTime
LocalDateTime start = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTimeMillis), ZoneId.systemDefault());
//将endTimeMillis转为LocalDateTime并且月份减少12
LocalDateTime end = LocalDateTime.ofInstant(Instant.ofEpochMilli(endTimeMillis), ZoneId.systemDefault())
.minusMonths(12);
//如果end和start相等,或者end在start之前,说明没有超过12个月
//start:2022-05-01 end:2022-05-08 --> end:2021-05-08
//end在start之前即起止时间没有超过12个月
return end.isEqual(start) || end.isBefore(start) ? false : true;
}