Get Last Friday of Month in Java

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

    java.time

    Using java.time library built into Java 8 and later, you may use TemporalAdjusters.lastInMonth:

    val now = LocalDate.now() 
    val lastInMonth = now.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))
    

    You may choose any day from the DayOfWeek enum.

    If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like

    lastFriday.atStartOfDay() // e.g. 2015-11-27T00:00
    

提交回复
热议问题