java 每隔一段时间_java获取一段时间的每一天

一、概述

在写java代码过程遇到一个场景,给定开始和结束日期需要判断这段时间的哪一天在数据库中不存在,所以需要获取这段时间的每一天,查阅了网上的资料这里做一个总结,方便自己理解也希望能帮助到其他同学。

二、代码实现如下

1、java8之前的实现方式

public static void main(String[] args) {

System.out.println(findDates("2020-02-02", "2020-03-03"));

}

public static List findDates(String startTime, String endTime) {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

List dateList = new ArrayList<>();

try {

// 使用SimpleDateFormat将字符串转换为Date

Date startDate = sdf.parse(startTime);

// 使用SimpleDateFormat将字符串转换为Date

Date endDate = sdf.parse(endTime);

// 获取Calendar的实例

Calendar startCal = Calendar.getInstance();

// 将开始的Date设置到Calendar中

startCal.setTime(startDate);

// 将开始时间添加到列表中

dateList.add(startTime);

// 判断如果endDate在startDate之后则为true

while (endDate.after(startCal.getTime())) {

// 在当前时间的基础上加一天

startCal.add(Calendar.DAY_OF_MONTH, 1);

// 添加到列表中

dateList.add(sdf.format(startCal.getTime()));

}

} catch (ParseException e) {

e.printStackTrace();

}

return dateList;

}

二、使用java8的LocalDate实现

public static void main(String[] args) {

System.out.println(getBetweenDate("2020-02-02", "2020-03-03"));

}

public static List getBetweenDate(String start, String end) {

List list = new ArrayList<>();

// LocalDate默认的时间格式为2020-02-02

LocalDate startDate = LocalDate.parse(start);

LocalDate endDate = LocalDate.parse(end);

long distance = ChronoUnit.DAYS.between(startDate, endDate);

if (distance < 1) {

return list;

}

Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(f -> list.add(f.toString()));

return list;

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值