java中获取当前时间、本周、本月、当前季度、年度的开始时间与结束时间

项目中的大屏统计经常会用到根据时间去统计相关数据,所以就需要获取相应的开始时间与结束时间,以便在sql中能查询出对应区间的数据。

代码直接复制就可以用,返回的数据就是开始时间与结束时间。

public String getTime(String dateType) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if ("1".equals(dateType)) {
            //今日
            LocalDateTime dayStart = now.with(LocalTime.MIN);
            LocalDateTime dayEnd = now.with(LocalTime.MAX);
            return dayStart.format(fmt) + "," + dayEnd.format(fmt);
        } else if ("2".equals(dateType)) {
            //本周
            int dayOfWeek = now.getDayOfWeek().getValue();
            LocalDateTime weekStart = now.minusDays(dayOfWeek - 1).with(LocalTime.MIN);
            LocalDateTime weekEnd = now.plusDays(7 - dayOfWeek).with(LocalTime.MAX);
            return weekStart.format(fmt) + "," + weekEnd.format(fmt);
        } else if ("3".equals(dateType)) {
            //本月
            LocalDateTime monthStart = now.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
            LocalDateTime monthEnd = now.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
            return monthStart.format(fmt) + "," + monthEnd.format(fmt);
        } else if ("4".equals(dateType)) {
            LocalDate date = LocalDate.now();
            LocalDate quarterStart = getStartOrEndDayOfQuarter(date, true);
            LocalDate quarterEnd = getStartOrEndDayOfQuarter(date, false);
            return quarterStart.format(fmt) + "," + quarterEnd.format(fmt);
        } else {
            //本年
            LocalDateTime yearStart = now.with(TemporalAdjusters.firstDayOfYear()).with(LocalTime.MIN);
            LocalDateTime yearEnd = now.with(TemporalAdjusters.lastDayOfYear()).with(LocalTime.MAX);
            return yearStart.format(fmt) + "," + yearEnd.format(fmt);
        }
    }
    public static LocalDate getStartOrEndDayOfQuarter(LocalDate today, Boolean isFirst) {
        LocalDate resDate = LocalDate.now();
        if (today == null) {
            today = resDate;
        }
        Month month = today.getMonth();
        Month firstMonthOfQuarter = month.firstMonthOfQuarter();
        Month endMonthOfQuarter = Month.of(firstMonthOfQuarter.getValue() + 2);
        if (isFirst) {
            resDate = LocalDate.of(today.getYear(), firstMonthOfQuarter, 1);
        } else {
            resDate = LocalDate.of(today.getYear(), endMonthOfQuarter, endMonthOfQuarter.length(today.isLeapYear()));
        }
        return resDate;
    }

 

拿到返回值,将其以逗号分隔开就可以用了(参数的dateType值需要前端传,前端选择相应的时间,比如前端传3,那就是获取当前时间的本月开始时间与结束时间)

  • 13
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值