Write a Java program to get the number of days of a month


The code you provided is a Java program that uses the java.util package to get the number of days in the current month and print it to the console. Here is a breakdown of the code:

  • The java.util package is imported at the beginning of the code.
  • The NumberDays_Month class is defined, which contains the main method.
  • Within the main method, a new Calendar object is created with getInstance(), which returns a calendar instance based on the current time in the default timezone and default locale of the system.
  • The getActualMaximum() method is called on the cal variable with the Calendar.DAY_OF_MONTH parameter, which returns the maximum value that the day of the month field can have for the current month. This value represents the number of days in the current month. The result is stored in the num_days variable.
  • The number of days in the current month is printed to the console using the System.out.println() method.

Source Code

import java.util.*;
public class NumberDays_Month
{
	public static void main(String []args)
	{
		Calendar cal = Calendar.getInstance();
		int num_days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		System.out.println("Number of Days in Current Month : " + num_days);
	}
}

Output

Number of Days in Current Month : 30

Example Programs