Write a Java program to get the name of the first and last day of a month


The code you provided is a Java program that uses the java.time and java.text packages to get the name of the first and last day of a specified month and year and print them to the console. Here is a breakdown of the code:

  • The java.time and java.text packages are imported at the beginning of the code.
  • The FirstLast_DayMonth class is defined, which contains the main method.
  • Within the main method, a new YearMonth object is created with the of() method, which takes the year and month as parameters. In this case, the year is set to 2023 and the month is set to March.
  • The atDay() method is called on the ym variable with the parameter 1, which returns a LocalDate object representing the first day of the month. The getDayOfWeek() method is then called on this LocalDate object, which returns a DayOfWeek object representing the day of the week. The name() method is called on this DayOfWeek object, which returns the name of the day of the week as a string. This string is stored in the fday variable.
  • The atEndOfMonth() method is called on the ym variable, which returns a LocalDate object representing the last day of the month. The getDayOfWeek() method is then called on this LocalDate object, which returns a DayOfWeek object representing the day of the week. The name() method is called on this DayOfWeek object, which returns the name of the day of the week as a string. This string is stored in the lday variable.
  • The name of the first day of the month and the name of the last day of the month are printed to the console using the System.out.println() method.

Source Code

import java.time.*;
import java.text.*;
public class FirstLast_DayMonth
{
	public static void main(String []args)
	{
		YearMonth ym = YearMonth.of(2023, 3);
		String fday = ym.atDay(1).getDayOfWeek().name();
		String lday = ym.atEndOfMonth().getDayOfWeek().name();
		System.out.println(fday);
		System.out.println(lday);
	}
}

Output

WEDNESDAY
FRIDAY

Example Programs