How to Get Number of Days from Month and Year using LocalDate in Java



This example shows how to get a number of days from month and year using LocalDate in Java.

LocalDate represents a year-month-day in the ISO calendar and is useful for representing a date without a time. You might use a LocalDate to track a significant event, such as birth date or wedding date.

Read more about LocalDate class with an example at https://www.javaguides.net/2018/08/java-8-localdate-class-api-guide.html.

Get Number of Days from Month and Year using LocalDate in Java

The LocalDate class provides below APIs to get a number of days from Month or Year from LocalDate.
  • int lengthOfMonth() - Returns the length of the month represented by this date.
  • int lengthOfYear() - Returns the length of the year represented by this date.
import java.time.LocalDate;
import java.time.Month;
/**
 * Program to demonstrate LocalDate Class APIs.
 * @author javaguides.net
 *
 */
public class LocalDateExamples {
 
    public static void main(String[] args) {
         getDaysFromMonthAndYear();
    }
 
    private static void getDaysFromMonthAndYear() {
        LocalDate localDate1 = LocalDate.of(2017, Month.JANUARY, 1);
        LocalDate localDate2 = LocalDate.of(2016, Month.FEBRUARY, 1);

        // Number of days in a month
        System.out.println("Number of days in " + localDate1.getMonth() + " : " + localDate1.lengthOfMonth());
        System.out.println("Number of days in " + localDate2.getMonth() + " : " + localDate2.lengthOfMonth());
 
        // Number of days in a year
        System.out.println("Number of days in " + localDate1.getYear() + " : " + localDate1.lengthOfYear());
        System.out.println("Number of days in " + localDate2.getYear() + " : " + localDate2.lengthOfYear());
    }
}
Output:
Number of days in JANUARY : 31
Number of days in FEBRUARY : 29
Number of days in 2017 : 365
Number of days in 2016 : 366

Reference

https://www.javaguides.net/2018/08/java-8-localdate-class-api-guide.html

Comments