java生成日期列表/日期序列

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class DateUtil {

  private static final String pattern = "yyyyMMdd";
  private static final DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(pattern);
  
  public static List<String> getDayList(String startDate, int gap) {
    // 生成年月日的日期序列
    List<String> res = new ArrayList<>();
    for (int i = 0; i < gap; i++) {
      LocalDate newDate = LocalDate.parse(startDate, dateFormat).plusDays(i);
      String dateString = dateFormat.format(newDate);
      res.add(dateString);
    }
    return res;
  }

  public static List<String> getDayList(String startDate, String endDate) {
    // 生成年月日的日期序列
    List<String> res = new ArrayList<>();
    LocalDate
        newStartDate =
        LocalDate.parse(startDate, dateFormat).minusDays(1);  // 这里先对startDate减一天,最后的结果才能包含startDate
    LocalDate newEndDate = LocalDate.parse(endDate, dateFormat);
    while (!newStartDate.equals(newEndDate)) {
      newStartDate = newStartDate.plusDays(1);
      String dateString = dateFormat.format(newStartDate);
      res.add(dateString);
    }
    return res;
  }

  public static List<String> getDayList(int gap, String endDate) {
    // 生成年月日的日期序列
    List<String> res = new ArrayList<>();
    for (int i = gap - 1; i >= 0; i--) {
      LocalDate newDate = LocalDate.parse(endDate, dateFormat).minusDays(i);
      String dateString = dateFormat.format(newDate);
      res.add(dateString);
    }
    return res;
  }

  public static void main(String[] args) {
    String startDate = "20201204";
    String endDate = "20201210";
    int gap = 7;

    // 输入起始日期和时间间隔
    List<String> dateList1 = getDayList(startDate, gap);
    // 输入起始日期和终止日期
    List<String> dateList2 = getDayList(startDate, endDate);
    // 输入时间间隔和终止日期
    List<String> dateList3 = getDayList(gap, endDate);

    System.out.println("dateList1:" + dateList1);
    System.out.println("dateList2:" + dateList2);
    System.out.println("dateList3:" + dateList3);
  }
}


dateList1:[20201204, 20201205, 20201206, 20201207, 20201208, 20201209, 20201210]
dateList2:[20201204, 20201205, 20201206, 20201207, 20201208, 20201209, 20201210]
dateList3:[20201204, 20201205, 20201206, 20201207, 20201208, 20201209, 20201210]

PS:
如果要设置日期为2020-12-10的形式,则需要修改pattern,并修改输入的日期格式

  private static final String pattern = "yyyy-MM-dd";
  ...skip...
  String startDate = "2020-12-04";
  String endDate = "2020-12-10";

其他相关博客
python 生成日期列表

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值