LocalDate使用简记

业务场景

这里以 苍穹外卖 的营业额统计功能 为例,记录下 LocalDate 的使用,方便日后自己回顾。
Controller 层

@RestController
@RequestMapping("/admin/report")
@Slf4j
public class ReportController {

    @Autowired
    private ReportService reportService;

    /**
     * @Author Feng
     * @Description 营业额统计
     * @Date 2024/8/4
     * @Param
     * @return
     **/
    @GetMapping("/turnoverStatistics")
    public Result<TurnoverReportVO> turnoverStatistics (
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end){
        log.info("营业额统计,开始时间:{}", begin);
        TurnoverReportVO turnoverReportVO = reportService.getTurnoverReport(begin, end);
        return Result.success(turnoverReportVO);
    }
}

service层

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * @Author Feng
     * @Description 营业额统计
     * @Date 2024/8/4
     * @Param
     * @return
     **/
    @Override
    public TurnoverReportVO getTurnoverReport(LocalDate begin, LocalDate end) {
        // 1. 计算有多少天数,以列表形式保存
        List<LocalDate> dates = new ArrayList<>();
        dates.add(begin);

        while (!end.equals(begin)) {
            begin = begin.plusDays(1);
            dates.add(begin);
        }

        // 2. 查询每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dates) {
            // 每天开始的时间,即零点
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // 每天结束的时间,即23点59分59秒99999999毫秒
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dates, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return turnoverReportVO;
    }
}

在 service 层,接收到 controller 层传入的LocalDate类型参数 begin 和 end,其形式为 年-月-日,即 2024-08-04 形式,要想得到 年-月-日:时:分:秒类型,可使用LocalDateTime类的 of() 方法,借助 LocalTime.MIN 以及 LocalTime.MAX 变量得到每天的零点以及24点。

LocalDate、LocalTime、LocalDateTime

这里简单介绍这三个类的区别

  • LocalDate: 表示日期,(年月日)
  • LocalTime:表示时间(时分秒)
  • LocalDateTime:表示日期+时间(年月日时分秒)
    这三个类都是线程安全的。
    这里贴上这个大佬的对这三个类的介绍链接,方便自己日后学习。
    https://blog.csdn.net/qq_44749491/article/details/130123065
  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值