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

前端 未结 8 1650
执笔经年
执笔经年 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条回答
  •  猫巷女王i
    2020-12-09 11:37

    To do date arithmetic in Java (and in general, to do anything with datetimes, except for the most trivial things) Joda-Time is the answer:

    public static LocalDate getNDayOfMonth(int dayweek,int nthweek,int month,int year)  {
       LocalDate d = new LocalDate(year, month, 1).withDayOfWeek(dayweek);
       if(d.getMonthOfYear() != month) d = d.plusWeeks(1);
       return d.plusWeeks(nthweek-1);
    }
    
    public static LocalDate getLastWeekdayOfMonth(int dayweek,int month,int year) {
       LocalDate d = new LocalDate(year, month, 1).plusMonths(1).withDayOfWeek(dayweek);
       if(d.getMonthOfYear() != month) d = d.minusWeeks(1);
      return d;
    }
    
    public static void main(String[] args) {
       // second wednesday of oct-2011
       LocalDate d = getNDayOfMonth( DateTimeConstants.WEDNESDAY, 2, 10, 2011);
       System.out.println(d);
       // last wednesday of oct-2011
       LocalDate dlast = getLastWeekdayOfMonth( DateTimeConstants.WEDNESDAY,  10, 2011);
       System.out.println(dlast);
    }
    

    Edit: Since Java 8 (2014) the new Date API (package java.time), which is inspired by/similar to Jodatime, should be preferred.

提交回复
热议问题