0


Java获取今天、本周、本月、本季度、上月、上一年的时间范围

1、获取本月的第一天和最后一天

// 本月第一天DateTime firstDay =DateUtil.beginOfMonth(newDate());// 本月最后一条Date lastDay =DateUtil.endOfMonth(newDate());

2、获取今天的时间范围

DateTime beginOfDay =DateUtil.beginOfDay(newDate());// 2023-09-25 00:00:00DateTime endOfDay =DateUtil.endOfDay(newDate());// 2023-09-25 23:59:59

3、获取本周的第一天和最后一天

DateTime beginOfWeek =DateUtil.beginOfWeek(newDate());Date endOfWeek=DateUtil.endOfWeek(newDate());

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(newDate());DateTime endOfQuarter =DateUtil.endOfQuarter(newDate());

6、获取今年的第一天和最后一天

DateTime beginOfYear =DateUtil.beginOfYear(newDate());DateTime endOfYear =DateUtil.endOfYear(newDate());

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

本文转载自: https://blog.csdn.net/YYbLQQ/article/details/133277771
版权归原作者 程序小媛! 所有, 如有侵权,请联系我们删除。

“Java获取今天、本周、本月、本季度、上月、上一年的时间范围”的评论:

还没有评论