Get Last Friday of Month in Java

后端 未结 16 1960
一生所求
一生所求 2020-11-28 11:28

I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Ja

16条回答
  •  再見小時候
    2020-11-28 12:04

    Slightly easier to read, brute-force approach:

    public int getLastFriday(int month, int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, 1, 0, 0, 0); // set to first day of the month
        cal.set(Calendar.MILLISECOND, 0);
    
        int friday = -1;
        while (cal.get(Calendar.MONTH) == month) { 
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { // is it a friday?
                friday = cal.get(Calendar.DAY_OF_MONTH);
                cal.add(Calendar.DAY_OF_MONTH, 7); // skip 7 days
            } else {
                cal.add(Calendar.DAY_OF_MONTH, 1); // skip 1 day
            }
        }
        return friday;
    }
    

提交回复
热议问题