How to find the first day and last day of the week. (day means date) in JAVA

Find the first day and last day of the week

 

This Java program finds the first day and last day of the week using the java.util.Calendar class. It sets the calendar to the current week’s Monday and adds 6 days to get the last day of the week. The program then prints the first and last day of the week to the console.

Find the first day and last day of the week in JAVA

import java.util.*;

public class FirstAndLastDayOfWeek {
    public static void main(String[] args) {
        
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        System.out.println("First day of the week: " + calendar.getTime());

        calendar.add(Calendar.DATE, 6);

        System.out.println("Last day of the week: " + calendar.getTime());
    }
}

Output:

First day of the week: Mon Jul 29 12:07:15 IST 2024
Last day of the week: Sun Aug 04 12:07:15 IST 2024

 

This Java program uses the java.util.Calendar class to find the first day and last day of the week. It begins by creating a Calendar object that represents the current date and time. The program sets the DAY_OF_WEEK field of the Calendar object to Calendar.MONDAY, effectively setting it to the first day of the current week. The first day of the week is then printed to the console using the getTime() method of the Calendar object.

To determine the last day of the week, the program adds 6 days to the Calendar object using the add() method with the DATE field. Afterward, the last day of the week is printed to the console. By following these steps, the program successfully finds and displays the first and last day of the week. It’s important to note that the Calendar class is part of the legacy java.util package.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top