Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA - How to work out last day of a month entered by the user

Tags:

java

If the user enters a numerical value 1-12 for a month, how can I change my code below so that it outputs the maximum number of days for that month entered by user.

import java.util.*;

public class LastDay {
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);       
    GregorianCalendar cal = new GregorianCalendar();

    int myMonth;

    System.out.println("Enter the month number (1-12): ");
    myMonth = scanner.nextInt();

    System.out.println("Maximum number of days is: " + Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));     
}

}

At the moment it outputs the max number of days for month we're currently in (March). I would like for it to do it for myMonth value entered by user.

like image 971
Khalid Avatar asked Feb 17 '23 00:02

Khalid


2 Answers

At the moment it outputs the max number of days for month we're currently in (March).

Calendar.getInstance() returns current time, thus current month. You should:

 Calendar calendar = Calendar.getInstance();
 calendar.set(Calendar.MONTH, myMonth - 1);
 int actualMax = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
like image 105
ogzd Avatar answered May 01 '23 07:05

ogzd


You must set the month before:

GregorianCalendar cal = new GregorianCalendar();
cal.set(Calendar.MONTH, myMonth - 1);

System.out.println("Maximum number of days is: " + cal.getActualMaximum(Calendar.DAY_OF_MONTH));
like image 42
TheEwook Avatar answered May 01 '23 06:05

TheEwook