Determine how many days in a given month

Rajith Jayathunga :

I am doing some calculations based on no of days in a given month,

Determine current Year Month

Date date = new Date();
Year = YearFormat.format(date);
Month = MonthFormat.format(date);

Determine how many days in the current month

int year = Integer.valueOf(Year);
int month = Integer.valueOf(Month);
Calendar calendarD = new GregorianCalendar(year, month, 1);
int noOfDaysOfMonth = calendarD.getActualMaximum(Calendar.DAY_OF_MONTH);

Problem

noOfDaysOfMonth seems not giving me the correct no of days.

For example year = 2018 , month = 8 gave me 30 which I expect 31

snr :

LengthOfMonth method is for that. Besides, I think Calendar API shouldn't be used anymore. It is already old.

LocalDate date = LocalDate.of(2019, 6, 20);
int days = date.lengthOfMonth();

5 Reasons Why Java's old Date and Calendar API was Bad

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111731&siteId=1