Search code examples
javajava-8

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


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 in Java 8.

LocalDate now = LocalDate.now();
System.out.println(now.withDayOfWeek(DateTimeConstants.MONDAY));

I can not call 'withDayOfWeek()', because it does not exist.

So my question is: How to get the date of the first day of the week based on some LocalDate?


Solution

  • Note that the expression System.out.println(now.with(DayOfWeek.MONDAY)) is locale-independent as it uses ISO-8601, therefore it always jumps backwards to last Monday (or stays on Monday in case date points to Monday already).

    As such in US or some other countries - where week starts on Sunday - it may not work as you would expect - now.with(DayOfWeek.MONDAY) will not jump forward to Monday, in case date points to Sunday.

    In case you need to address these concerns, it is better to use the localized field WeekFields.dayOfWeek():

    LocalDate now = LocalDate.now();
    TemporalField fieldISO = WeekFields.of(Locale.FRANCE).dayOfWeek();
    System.out.println(now.with(fieldISO, 1)); // 2015-02-09 (Monday)
    
    TemporalField fieldUS = WeekFields.of(Locale.US).dayOfWeek();
    System.out.println(now.with(fieldUS, 1)); // 2015-02-08 (Sunday)
    

    Another example due to comments below:

    LocalDate ld = LocalDate.of(2017, 8, 18); // Friday as original date
    
    System.out.println(
        ld.with(DayOfWeek.SUNDAY)); // 2017-08-20 (2 days later according to ISO)
    
    // Now let's again set the date to Sunday, but this time in a localized way...
    // the method dayOfWeek() uses localized numbering (Sunday = 1 in US and = 7 in France)
    
    System.out.println(ld.with(WeekFields.of(Locale.US).dayOfWeek(), 1L)); // 2017-08-13
    System.out.println(ld.with(WeekFields.of(Locale.FRANCE).dayOfWeek(), 7L)); // 2017-08-20
    

    The US-example makes pretty clear that someone residing in US would expect to go to last and not to next Sunday because Sunday is considered as first day of week in US. The simple ISO-based expression with(DayOfWeek.SUNDAY) ignores this localization issue.