Java Program to get the beginning and end date of the week

Java 8Object Oriented ProgrammingProgramming

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

Now, get the date for the end of the week:

LocalDate end = date;
while (end.getDayOfWeek() != DayOfWeek.SUNDAY) {
   end = end.plusDays(1);
}

Example

import java.time.DayOfWeek;
import java.time.LocalDate;
public class Demo {
   public static void main(String[] argv) {
      LocalDate date = LocalDate.of(2019, 4, 16);
      System.out.println("Date = " + date);
      LocalDate start = date;
      while (start.getDayOfWeek() != DayOfWeek.MONDAY) {
         start = start.minusDays(1);
      }
      System.out.println("Start of the Week = " + start);
      LocalDate end = date;
      while (end.getDayOfWeek() != DayOfWeek.SUNDAY) {
         end = end.plusDays(1);
      }
      System.out.println("End of the Week = " + end);
   }
}

Output

Date = 2019-04-16
Start of the Week = 2019-04-15
End of the Week = 2019-04-21
raja
Published on 24-Apr-2019 15:41:03
Advertisements