Write a Java program to calculate the first and last day of each week


This Java program calculates the first and last day of the current week using the Calendar class and DateFormat class. Here are the key points of the program:

  • import java.util.*; - This line imports all classes from the java.util package, which includes the Calendar class.
  • import java.time.*; - This line imports all classes from the java.time package, which includes the DateFormat class.
  • public class Calculate_FirstLastDay - This line defines a public class named Calculate_FirstLastDay.
  • public static void main(String []args) - This line defines the main method of the program, which is the entry point for the program.
  • Calendar cal = Calendar.getInstance(); - This line creates a new instance of the Calendar class using the getInstance() method.
  • cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); - This line sets the calendar's day of the week to Monday using the set() method.
  • DateFormat d = new SimpleDateFormat("EEEE dd/MM/yyyy"); - This line creates a new instance of the DateFormat class using the SimpleDateFormat class and specifies the format of the date string to be printed.
  • System.out.println(d.format(cal.getTime())); - This line prints the formatted date string for the first day of the week using the getTime() method to retrieve the calendar's date and the format() method to format the date string.
  • for (int i = 0; i <6; i++) { cal.add(Calendar.DATE, 1); } - This line adds one day to the calendar six times to calculate the last day of the week.
  • System.out.println(d.format(cal.getTime())); - This line prints the formatted date string for the last day of the week using the same method as in step 8.

In summary, this program uses the Calendar and DateFormat classes to calculate and print the first and last day of the current week in a specified format.

Source Code

import java.util.*;
import java.time.*;
import java.text.*;
 
public class Calculate_FirstLastDay
{
	public static void main(String []args)
	{
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		DateFormat d = new SimpleDateFormat("EEEE dd/MM/yyyy");
		System.out.println(d.format(cal.getTime()));
		for (int i = 0; i <6; i++)
		{
			cal.add(Calendar.DATE, 1);
		}
		System.out.println(d.format(cal.getTime()));
	}
}

Output

Monday 31/10/2022
Sunday 06/11/2022

Example Programs