How to know how many days has particular month of particular year?
String date = "2010-01-19";
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
int daysQty = calendar.getDaysNumber(); // Something like this
Simple as that,no need to import anything
Java 8 and later
@Warren M. Nocos. If you are trying to use Java 8's new Date and Time API, you can use
java.time.YearMonth
class. See Oracle Tutorial.Test: try a month in a leap year:
Java 7 and earlier
Create a calendar, set year and month and use
getActualMaximum
Test: try a month in a leap year:
You can use Calendar.getActualMaximum method:
And month-1 is Because of month takes its original number of month while in method takes argument as below in Calendar.class
And the (int field) is like as below.
The use of outdated
Calendar
API should be avoided.In Java8 or higher version, this can be done with
YearMonth
.Example code:
In Java8 you can use get ValueRange from a field of a date.
This allows you to parameterize on the field.