I need to find the first day of the last week of a year using Java 8 Date and Time API (java.time) and finally came to this solution:
LocalDate date = LocalDate.of(2016, 2, 17);
LocalDate lastWeekOfYear = LocalDate.of(date.getYear() + 1, 1, 7)
.with(WeekFields.ISO.weekOfYear(), 1)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).minusDays(7);
This solution finds the first week of the next year, adjusts the day of week to Monday if necessary and moves 7 days back. Is there a smarter way to achieve the same result?
HOW TO FIND DAY OF A GIVEN DATE IN JAVA. To find the day of a given number in Java, the date is given as input, we will use Calendar class, which is an abstract class that allows us to use the methods for converting between a specific instant in time and a set of calendar fields such as: Year. Month. Day of Month. Hour.
2. Problem Business logic often needs the day of the week. Why? For one, working hours and service levels differ between workdays and weekends. Therefore, getting the day as a number is necessary for a lot of systems. But we also may need the day as a text for display. So, how do we extract the day of the week from dates in Java? 3.
Java Program to get the beginning and end date of the week. Java 8 Object Oriented Programming Programming. At first, set a date: LocalDate date = LocalDate.of (2019, 4, 16); Now, get the date for the beginning of the week: LocalDate start = date; while (start.getDayOfWeek () != DayOfWeek.MONDAY) { start = start.minusDays (1); }.
java.util.Date has been the Java date class since Java 1.0. Code that started with Java version 7 or lower probably uses this class. 3.1. Day of Week as a Number First, we extract the day as a number using java.util.Calendar: The resulting number ranges from 1 (Sunday) to 7 (Saturday).
As suggested, I'll answer the question myself (with a minor enhancement from the comments) as there does not seem to be a significantly simpler solution.
LocalDate date = LocalDate.of(2016, 2, 17);
LocalDate lastWeekOfYear = LocalDate.of(date.getYear() + 1, 1, 7)
.with(WeekFields.ISO.weekOfWeekBasedYear(), 1)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).minusWeeks(1);
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