Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the number of days in a month in Java

Tags:

How do you find the number of days in a month in Java?

like image 579
chetan Avatar asked Mar 30 '10 12:03

chetan


People also ask

How many days are in a month?

If the month is on a knuckle, it has 31 days. Otherwise is has 30 or less days.

How do you calculate months in Java?

yearsBetween() method to calcualte the number of months and years between two dates in Java. LocalDate jamesBirthDay = new LocalDate(1955, 5, 19); LocalDate now = new LocalDate(2015, 7, 30); int monthsBetween = Months.

How many days are there in the month denoted by A in a non leap year Java?

Number of days in any month of a year can vary specifically in February as the cycle of leap year repeats in every 4 years when the year is leap February gives the count to 29 days but the when the year is not leap it gives count to 28 days and so no of days in a year varies from 365 to 366.

What months have 31 days?

The months having 31 days in a year are January, March, May, July, August, October, and December.


2 Answers

Set the year and month on a Calendar object and then use getActualMaximum to return the last day:

calendar.getActualMaximum(Calendar.DAY_OF_MONTH)  
like image 192
Mark Byers Avatar answered Oct 03 '22 11:10

Mark Byers


Since Java 8, a simple way would be:

int daysInCurrentMonth = java.time.LocalDate.now().lengthOfMonth(); 
like image 42
Øyvind Mo Avatar answered Oct 03 '22 11:10

Øyvind Mo