Get date of first day of week based on LocalDate.now() in Java 8

前端 未结 9 1525
梦谈多话
梦谈多话 2020-12-02 19:35

I would like the get the date of the first day of the week based on LocalDate.now(). The following was possible with JodaTime, but seems to be removed from the new Date API

9条回答
  •  不知归路
    2020-12-02 20:21

    As the correct Answer by Ray says, you can call with and pass the DayOfWeek enum.

    Time zone

    Note that time zone is crucial in determining the date of "today". At any moment the date varies by where you are standing on the globe.

    ZoneId zoneId = ZoneId.of ( "America/Montreal" );
    LocalDate firstDayOfThisWeek = LocalDate.now ( zoneId ).with ( DayOfWeek.MONDAY );
    

    If you do not specify a time zone, the JVM’s current default time zone is silently applied. Beware: That default can change at any moment during runtime! Better to specify your desired/expected time zone.

    ZonedDateTime

    You can apply a time zone (a ZoneId) to your LocalDate to get a ZonedDateTime representing the first moment of the week.

    ZonedDateTime thisWeekStart = firstDayOfThisWeek.atStartOfDay ( zoneId );
    

提交回复
热议问题