1、获取本月的第一天和最后一天
// 本月第一天 DateTime firstDay = DateUtil.beginOfMonth(new Date()); // 本月最后一条 Date lastDay = DateUtil.endOfMonth(new Date());
2、获取今天的时间范围
DateTime beginOfDay = DateUtil.beginOfDay(new Date()); // 2023-09-25 00:00:00 DateTime endOfDay = DateUtil.endOfDay(new Date()); // 2023-09-25 23:59:59
3、获取本周的第一天和最后一天
DateTime beginOfWeek = DateUtil.beginOfWeek(new Date()); Date endOfWeek=DateUtil.endOfWeek(new Date());
4、获取上个月的时间范围
LocalDate currentDate = LocalDate.now(); // 当前日期 LocalDate previousMonthDate = currentDate.minusMonths(1); // 上个月日期 Month previousMonth = previousMonthDate.getMonth(); // 上个月的月份 int previousMonthYear = previousMonthDate.getYear(); // 上个月的年份 boolean leapYear = false; // 判断是否为闰年 if(previousMonthYear%4 == 0 && previousMonthYear%100 !=0 || previousMonthYear%400 == 0){ leapYear = true; } // 上个月的开始时间 LocalDateTime startOfPrevious = LocalDateTime.of(previousMonthYear, previousMonth, 1, 0, 0, 0); // 上个月的结束时间 LocalDateTime endOfPrevious = LocalDateTime.of(previousMonthYear, previousMonth, previousMonth.length(leapYear), 23, 59, 59); // 将LocalDateTime 转换为Date类型 ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTime startMonth = startOfPrevious.atZone(zoneId); ZonedDateTime endMonth = endOfPrevious.atZone(zoneId); Date beginOfPreviousMonth = Date.from(startMonth.toInstant()); Date endOfPreviousMonth = Date.from(endMonth.toInstant());
5、获取本季度的第一天和最后一天
DateTime beginOfQuarter = DateUtil.beginOfQuarter(new Date()); DateTime endOfQuarter = DateUtil.endOfQuarter(new Date());
6、获取今年的第一天和最后一天
DateTime beginOfYear = DateUtil.beginOfYear(new Date()); DateTime endOfYear = DateUtil.endOfYear(new Date());
7、获取上一年的第一天和最后一天
Year currentYear = Year.now(); // 当前年份 Year previousYear = currentYear.minusYears(1); // 上一年 // 上一年的开始时间 LocalDateTime previousYearStart = previousYear.atDay(1).atStartOfDay(); // 上一年的结束时间 LocalDateTime previousYearEnd = previousYear.atMonth(12).atEndOfMonth().atTime(23, 59, 59); // 将LocalDateTime 转换为Date类型 ZoneId zoneYearId = ZoneId.systemDefault(); ZonedDateTime zdt = previousYearStart.atZone(zoneYearId); ZonedDateTime end = previousYearEnd.atZone(zoneYearId); Date beginOfPreviousYear = Date.from(zdt.toInstant()); Date endOfPreviousYear = Date.from(end.toInstant());
上一篇:JAVA结课作品——超市管理系统