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?
LocalDate getDayOfWeek() method in Java The getDayOfWeek() method of LocalDate class in Java gets the day-of-week field, which is an enum DayOfWeek. Parameter: This method does not accepts any parameter. Return Value: The function returns the day of the week and not null.
Description. The java. time. LocalDate. now() method obtains the current date from the system clock in the default time-zone.
You can get the time from the LocaldateTime object using the toLocalTime() method. Therefore, another way to get the current time is to retrieve the current LocaldateTime object using the of() method of the same class. From this object get the time using the toLocalTime() method.
To get the day of the week, use Calendar. DAY_OF_WEEK.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With