You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Cron表达式获取指定起止日期之间的所有未来日期?

获取指定范围的所有Cron匹配日期(替代单次next调用)

我明白你现在的痛点——CronSequenceGenerator的next()方法只能返回下一个匹配的日期,但你需要的是给定起止日期范围内所有符合规则的未来日期。没问题,咱们基于Spring的这个工具类就能轻松实现,直接上代码和说明:

实现思路

核心逻辑很简单:通过循环调用next()方法,每次拿到下一个匹配日期,直到超出你设定的结束日期为止,把所有符合条件的日期收集起来。

工具方法代码

import org.springframework.scheduling.support.CronSequenceGenerator;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class CronDateFetcher {
    /**
     * 获取指定起止日期内符合Cron规则的所有日期
     * @param cronExpression 你的Cron表达式
     * @param startDate 起始日期(从该日期之后开始找匹配项)
     * @param endDate 结束日期(匹配项不能晚于这个日期)
     * @param timeZone 指定时区(可选,默认用系统时区)
     * @return 所有匹配的日期列表
     */
    public static List<Date> getAllMatchingDates(String cronExpression, Date startDate, Date endDate, TimeZone timeZone) {
        List<Date> matchingDates = new ArrayList<>();
        CronSequenceGenerator cron = timeZone != null 
            ? new CronSequenceGenerator(cronExpression, timeZone)
            : new CronSequenceGenerator(cronExpression);
        
        Date nextDate = cron.next(startDate);
        // 循环获取下一个日期,直到超出结束日期
        while (nextDate != null && !nextDate.after(endDate)) {
            matchingDates.add(nextDate);
            nextDate = cron.next(nextDate);
        }
        
        return matchingDates;
    }

    // 重载方法:使用系统默认时区
    public static List<Date> getAllMatchingDates(String cronExpression, Date startDate, Date endDate) {
        return getAllMatchingDates(cronExpression, startDate, endDate, null);
    }
}

关键细节说明

  • 时区处理:重载方法支持指定时区(比如TimeZone.getTimeZone("Asia/Shanghai")),避免因系统时区差异导致的日期偏差
  • 边界控制:代码中用!nextDate.after(endDate)确保结束日期当天的匹配项也会被包含;如果不需要包含结束日期,改成nextDate.before(endDate)即可
  • 空值处理:next()方法在没有更多匹配日期时会返回null,所以循环里加了nextDate != null的判断,避免空指针

使用示例

比如你想获取从今天开始,未来7天内每天早上9点的所有日期:

public static void main(String[] args) {
    String cron = "0 0 9 * * ?"; // 每天9点整
    Date start = new Date(); // 当前时间作为起始点
    Date end = new Date(System.currentTimeMillis() + 7L * 24 * 60 * 60 * 1000); // 7天后的时间
    
    List<Date> dates = CronDateFetcher.getAllMatchingDates(cron, start, end);
    dates.forEach(System.out::println);
}

这样就能得到你需要的完整日期列表啦!

内容的提问来源于stack exchange,提问作者boycod3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:50:21