背景:
前端入参分别有startDate和endDate,类型为字符串,格式为:2023-01-01、2023-05-01,需要后端计算出1月到5月的每一天
代码如下:
String startDateStr = res.getStartDate(); String endDateStr = res.getEndDate(); DateTime startDate = DateUtil.parse(startDateStr); DateTime endDate = DateUtil.parse(endDateStr); LocalDateTime endDateNew = endDate.toLocalDateTime().plusDays(endDate.getLastDayOfMonth() - 1); LocalDateTime start = LocalDateTimeUtil.parse(startDate.toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))); LocalDateTime end = LocalDateTimeUtil.parse(endDate.toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))); Duration between = LocalDateTimeUtil.between(start, endDateNew); long days = between.toDays(); log.info("相差天数 = " + days); // int startMonth = startDate.month() + 1; int endMonth = endDate.month() + 1; while (!start.isAfter(end)) { for (int i = 0; i < endMonth; i++) { // int monthDays = startDate.getLastDayOfMonth(); int monthDays = DateUtil.parse(start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).getLastDayOfMonth(); for (int j = 0; j < monthDays; j++) { log.info("month = " + (i+1) + ", monthDays = " + monthDays + ", start = " + start + ", days = " + days); start = start.plusDays(1); days--; if (days < 0) { break; } } } }
标签:startDate,java,int,hutool,days,parse,start,时间段,endDate From: https://www.cnblogs.com/jamstack/p/17414188.html