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

If a user enters a numeric value of 1-12 for a month, how can I change my code below so that it displays the maximum number of days for this month entered by the 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, he displays the maximum number of days in the month in which we are now (in March). I would like it to do this for myMonth value entered by the user.

+4
source share
6 answers

You should install a month earlier:

 GregorianCalendar cal = new GregorianCalendar(); cal.set(Calendar.MONTH, myMonth - 1); System.out.println("Maximum number of days is: " + cal.getActualMaximum(Calendar.DAY_OF_MONTH)); 
+1
source

At the moment, he displays the maximum number of days in the month in which we are now (in March).

Calendar.getInstance() returns the current time, that is, the current month. You must:

  Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MONTH, myMonth - 1); int actualMax = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 
+3
source

Create a new Calendar object and set its month to the value that the user enters -1 (starting from the month from 0 on the calendar.)

Then get the ActualMaximum of this Calendar

+1
source

The answer is more like a combination of the two previous answers.

For example, to get the maximum days of February, than myMonth will be 2

 public static void main(String[] args){ int myMonth = 2; Calendar c = Calendar.getInstance(); c.set(Calendar.MONTH, myMonth - 1); System.out.println(c.getActualMaximum(Calendar.DAY_OF_MONTH)); } 
+1
source

If you use Yoda, this is even easier:

 DateTime last = new DateTime(). withMonthOfYear(myMonth). dayOfMonth().withMaximumValue(); 
+1
source
  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(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, myMonth-1, Calendar.DATE); System.out.println("Maximum number of days is: " + calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); } 

}

+1
source

All Articles