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



In this article, we'll explore how to determine the start and end dates of a week using Java. Specifically, we'll write a program that takes a given date and calculates the Monday and Sunday of that week. 

Problem Statement

Write a Java program to find the beginning (Monday) and end (Sunday) dates of the week for a given date.

Input

Date = 2019-04-16

Output

Start of the Week = 2019-04-15
End of the Week = 2019-04-21

Steps to calculate week's start and end dates

Following are the steps to get the beginning and end date of the week ?

  • First, we'll set up the date using the LocalDate class from the java.time package.
  • Initialize the Date by using LocalDate to set a specific date.
  • To find the Monday we will loop backward with minusDays(1) until getDayOfWeek() returns DayOfWeek.MONDAY.
  • To find the Monday we will loop forward with plusDays(1) until getDayOfWeek() returns DayOfWeek.SUNDAY.
  • Display the original date, Monday, and Sunday.

Java program to calculate week's start and end dates

Below are the steps to get the beginning and end date of the week ?

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

Code Explanation

The program begins by setting a specific date using the LocalDate class from the java.time package. This allows us to work with dates easily. To find the start of the week, which is Monday, we loop backward from the given date using a while loop until the day of the week is Monday. This is done by repeatedly subtracting one day from the date with the minusDays() method. Similarly, to find the end of the week, which is Sunday, we loop forward from the original date until we reach Sunday, using the plusDays() method. The getDayOfWeek()` method is used within these loops to check the current day of the week.

Updated on: 2024-08-30T19:34:32+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements