Get Last Friday of Month in Java

后端 未结 16 1961
一生所求
一生所求 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:06

    I would use a library like Jodatime. It has a very useful API and it uses normal month numbers. And best of all, it is thread safe.

    I think that you can have a solution with (but possibly not the shortest, but certainly more readable):

    DateTime now = new DateTime();      
    DateTime dt = now.dayOfMonth().withMaximumValue().withDayOfWeek(DateTimeConstants.FRIDAY);
    if (dt.getMonthOfYear() != now.getMonthOfYear()) {
      dt = dt.minusDays(7);
    }       
    System.out.println(dt);
    

提交回复
热议问题