2

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

JustBaron
  • 2,319
  • 7
  • 25
  • 37

3 Answers3

6

LocalDate::lengthOfMonth

If you use Java 8, you can access the java.time API.

Specifically, the LocalDate::lengthOfMonth method.

int length = LocalDate.now().lengthOfMonth();
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Glains
  • 2,773
  • 3
  • 16
  • 30
  • 1
    Correct answer. Also, if working with months as a whole, the [`YearMonth`](https://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html) class may be useful. `YearMonth.now().lengthOfMonth()` – Basil Bourque Aug 03 '18 at 19:14
  • In other works, if your target API level is > 25, then you can use this. That is only 39% of the market share at the time of posting this comment... – ClassA Jun 11 '19 at 06:12
3

month starts with 0 = january; month = 8 ist september and september have just 30 days.

To avoid this use Calendar.AUGUST for exaxmple instead of 8.

René
  • 141
  • 1
  • 6
3

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