Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find first day of last week of year with java.time

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?

like image 287
Oxolotl Avatar asked May 12 '16 13:05

Oxolotl


People also ask

How do you find the day of a given date in Java?

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.

Why do we need the day of the week in Java?

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.

How to get the beginning and end date of the week?

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); }.

What is the date class in Java?

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).


1 Answers

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);
like image 121
Oxolotl Avatar answered Oct 08 '22 06:10

Oxolotl