Get Last Friday of Month in Java

后端 未结 16 1936
一生所求
一生所求 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 11:59

    Though I agree with scubabbl, here is a version without an inner while.

    int year = 2008;
    for (int m = Calendar.JANUARY; m <= Calendar.DECEMBER; m++) {
        Calendar cal = new GregorianCalendar(year, m, 1);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        int diff = Calendar.FRIDAY - cal.get(Calendar.DAY_OF_WEEK);
        if (diff > 0) {
            diff -= 7;
        }
        cal.add(Calendar.DAY_OF_MONTH, diff);
        System.out.println(cal.getTime());
    }
    

提交回复
热议问题