Get starting date of week(configurable starting day of week)

前端 未结 4 417
暖寄归人
暖寄归人 2021-01-20 04:57

I have current date, and a constant which tells from which day the week starts. I want to get the start date of the week based on that constant. If I hardcode the first day

4条回答
  •  梦谈多话
    2021-01-20 05:30

    tl;dr

    LocalDate.now( ZoneId.of( "America/Montreal" ) )
             .with( TemporalAdjusters.previousOrSame( DayOfWeek.SUNDAY ) )  // Specify your desired `DayOfWeek` as start-of-week.
             .atStartOfDay( ZoneId.of( "America/Montreal" ) )
    

    See this code run live at IdeOne.com.

    zdt: 2017-07-09T00:00-04:00[America/Montreal] | day-of-week: SUNDAY

    Avoid legacy classes

    You are using the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

    DayOfWeek

    Rather than use mere integer numbers to represent day-of-week in your code, use the DayOfWeek enum built into Java. This gains you type-safety, ensures valid values, and makes your code more self-documenting.

    DayOfWeek weekStart = DayOfWeek.SUNDAY ;  // Pass whatever `DayOfWeek` object you want.
    

    TemporalAdjuster & LocalDate

    The TemporalAdjuster interface enables ways to manipulate a date to get another date. Find some implementations in TemporalAdjusters class (note plural).

    ZoneId z = ZoneId.of( "America/Montreal" ) ;
    LocalDate today = LocalDate.now( z ) ;
    LocalDate start = today.with( TemporalAdjusters.previousOrSame( weekStart ) ) ;  
    

    ZonedDateTime

    To get an exact moment, ask the LocalDate for its first moment of the day. That moment depends on a time zone, as the date varies around the globe for any given moment.

    ZonedDateTime zdt = start.atStartOfDay( z ) ;
    

    Instant

    If you want to view that some moment as in UTC, extract an Instant object.

    Instant instant = zdt.toInstant() ;  // Same moment, different wall-clock time.
    

提交回复
热议问题