Java: How do I get the date of x day in a month ( e.g. Third Monday in February 2012)

前端 未结 8 1630
执笔经年
执笔经年 2020-12-09 10:44

I am somewhat struggling with this.

I want to setup my Calendar to let\'s say: Third Monday in February 2012. And I didn\'t find any way of doing th

8条回答
  •  暖寄归人
    2020-12-09 11:37

    Any chances you are using Quartz scheduler?

    public Date date(String cronExpression) {
        return new org.quartz.CronExpression(cronExpression).
            getNextValidTimeAfter(new Date(0));
    }
    
    System.out.println(date("0 0 0 ? May Thu#3 2015"));
    System.out.println(date("0 0 0 ? Jun Mon#1 2050"));
    System.out.println(date("0 0 0 ? Dec Tue#4 2012"));
    System.out.println(date("0 0 0 ? Jul Wed#2 2000"));
    

    This simple code prints correct (?) results:

    Thu May 21 00:00:00 CEST 2015
    Mon Jun 06 00:00:00 CEST 2050
    Tue Dec 25 00:00:00 CET 2012
    Wed Jul 12 00:00:00 CEST 2000
    

    The required CronExpression doesn't have any dependencies on the rest of Quartz, so you might consider copying it to your project (watch out for license!)

    Side note: the internal implementation of getNextValidTimeAfter() is 400 lines of code...

提交回复
热议问题