LocalDateTime应用比较日期
//需求1:当天的日期且时间在9~24点之间的开始时间 LocalDateTime nowTime= LocalDateTime.now(); int year = nowTime.getYear(); int month = nowTime.getMonthValue(); int day = nowTime.getDayOfMonth(); System.out.println("year=" + year); System.out.println("month=" + month); System.out.println("day=" + day); // nowTime.withHour(9); // System.out.println("nowTime=" + nowTime ); LocalDateTime rentTime = LocalDateTime.of(2023, 3, 2, 9, 00, 00); int rentTimeyear = rentTime.getYear(); int rentTimemonth = rentTime.getMonthValue(); int rentTimeday = rentTime.getDayOfMonth(); int rentTimeHour = rentTime.getHour(); System.out.println("year=" + rentTimeyear); System.out.println("month=" + rentTimemonth); System.out.println("day=" + rentTimeday); System.out.println("rentTimeHour=" + rentTimeHour); //方法1:比较年月日int ,然后取小时数判断 if(year == rentTimeyear && month == rentTimemonth && day == rentTimeday){ System.out.println("日期符合"); if(rentTimeHour >= 9 && rentTimeHour <= 24){ System.out.println("小时符合"); }else { System.out.println("小时不符合"); } }else{ System.out.println("日期不符合"); } System.out.println("-------------------------------------------"); //方法2:通过localdatetime 来比较,设置localtime解决 LocalDate ld = LocalDate.now(); // LocalDateTime ldt1 = ld.atTime(8,59,59); // LocalDateTime ldt2 = ld.atTime(23,59,59); // System.out.println("ldt1="+ldt1); // System.out.println("ldt2="+ldt2); // Localtime转为 LocalDateTime LocalTime lt1 = LocalTime.of(8,59,59); LocalTime lt2 = LocalTime.of(23,59,59); LocalDateTime ldt1 = ld.atTime(lt1); LocalDateTime ldt2 = ld.atTime(lt2); System.out.println("ldt1="+ldt1); System.out.println("ldt2="+ldt2); // LocalDateTime localDateTime = LocalTime.now().atDate(LocalDate.now()); /** * 对于 date1.isAfter(date2) 代表的意思是, 检查 date1 是否在 date2 日期之后。 * 对于 date1.isBefore(date2) 代表的意思是,检查date1 是否在 date2 日期之前。 */ //含等于 rentTime.isEqual(ldt1) || 可以调整参考对象 if(rentTime.isAfter(ldt1) && rentTime.isBefore(ldt2)){ System.out.println("-------------符合要求"); }else{ System.out.println("不符合要求"); } //需求2:判断当前时间跟开始时间的比较,是否在距离开始时间4小时内 LocalDateTime rentTime2 = LocalDateTime.of(2023, 3, 13, 19, 53, 00); LocalDateTime now = LocalDateTime.now(); LocalDateTime rentTimeBefore4Hours = rentTime2.plusHours(-4); //4小时内 if(now.isAfter(rentTimeBefore4Hours)){ //券核销 System.out.println("4小时内"); }else{ System.out.println("4小时外"); }