2

Note: Donot mark it duplicate, I know it is duplicate question but I didn't get help from it.

I want to calculate Number Of Days in a month of particular year. I read this and but it is NOT working fine. I tried following

public class NumOfDays {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.print("Enter month: ");
        int month = input.nextInt();
        System.out.print("Enter year: ");
        int year = input.nextInt();

        Calendar mycal = new GregorianCalendar(year, month, 1);

        System.out.println("Number of days are: " + mycal.getActualMaximum(Calendar.DAY_OF_MONTH));

    }
}

My Console is

Enter month: 2
Enter year: 2000
Number of days are: 31 /// Wrong

and

Enter month: 10
Enter year: 1999
Number of days are: 30 // Correct

I know that there are one other method i.e. to calculate it manually, but I want to do it like above. Please let me know if I am doing anything wrong.

P.S: I am using JAVA-8.

Community
  • 1
  • 1
Junaid
  • 2,572
  • 6
  • 41
  • 77

3 Answers3

10

Since you are using Java 8 I suggest using the new date/time API, java.time, specifically its YearMonth class:

YearMonth ym = YearMonth.of(2000, 2);
System.out.println(ym.lengthOfMonth()); //29 as expected
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
assylias
  • 321,522
  • 82
  • 660
  • 783
7

Wasn't there 31 days in March 2000? Month is zero based, as the doc say (http://docs.oracle.com/javase/8/docs/api/java/util/GregorianCalendar.html#GregorianCalendar-int-int-int-)

Edit: I'm stupid, I thought you had the number of days in a month figured out. You need to use getActualMaximum, not get. (http://docs.oracle.com/javase/8/docs/api/java/util/GregorianCalendar.html#getActualMaximum-int-)

JP Moresmau
  • 7,388
  • 17
  • 31
0

following will work for sure...

public class NumberOfDays

{

public static void main(String g[])

{

Scanner scanner=new Scanner(System.in);

    int days,month,year,date;

    System.out.println("enter year= ");
    year=scanner.nextInt();

    System.out.println("enter month= ");
    month=scanner.nextInt();

    date=1;

    Calendar calendar=Calendar.getInstance();

    calendar.set(year, (month-1), date);

    days=calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

    System.out.println("max day= "+days);
}

}