FIND NUMBER OF DAYS IN A GIVEN MONTH IN JAVA

In this topic, we will explore easily and interestingly how to find the number of days in a given month in Java.

We can use the `YearMonth` class from the `java.time` package. Here’s a step-by-step explanation:

1. Choose a Month: Select the month for which you want to find the number of days.

Example: Let’s find the number of days in February 2024.

2. Use YearMonth Class: Instantiate a `YearMonth` object with the year and month for which you want to find the days.

Program:

 

import java.time.YearMonth;
import java.time.Month;

public class DaysInMonthExample {
public static void main(String[] args) {

int year = 2024;
Month month = Month.FEBRUARY;


YearMonth yearMonth = YearMonth.of(year, month);

int daysInMonth = yearMonth.lengthOfMonth();


System.out.println("Number of days in " + month + " " + year + " is: " + daysInMonth);
}
}

 

In this example:

  •  We set `year` to 2024 and `month` to `Month.FEBRUARY`
  • `YearMonth.of(year, month)` creates a `YearMonth` object representing February 2024
  •  `.lengthOfMonth()` method on `YearMonth` calculates and returns the number of days in that month.

3. Output: Print or use `daysInMonth`, which now holds the number of days in February 2024.

Explanation:

YearMonth: Represents a year and month, allowing you to easily query properties of that month, such as the number of days.

lengthOfMonth(): Method provided by `YearMonth` class that gives the number of days in the represented month.

Output:

Number of days in FEBRUARY 2024 is: 29

By following these steps, you can accurately determine the number of days in any given month in Java. Adjust the `year` and `month` variables as needed to find the days for different months and years.

Thank you for visiting our site!!!…..

Leave a Comment

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

Scroll to Top