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

前端 未结 8 1628
执笔经年
执笔经年 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:41

    Here is an alternative. What it does is: Get which week you want (n), and the other parameters, and return the date of the day in that week. Since Calendar gives the date of the previous month (for example 29th of February instead of 7th of March, since the 1st week of March collides with last week of Feb), the function computes the 2nd week if the date goes beyond 7 or multiples of it for each week thereof. Hope that helps.

    public static int getNthWeekDay (int n, int day, int month, int year) {
        Calendar calendar = Calendar.getInstance();
    
        calendar.set(Calendar.DAY_OF_WEEK, day);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.WEEK_OF_MONTH,n);
        calendar.set(Calendar.YEAR, year);
        if (calendar.get(Calendar.DATE) > n * 7) {
            calendar.set(Calendar.DAY_OF_WEEK,day);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.WEEK_OF_MONTH,day+1);
    
        }
        return calendar.get(Calendar.DATE);
    }
    

提交回复
热议问题