You can use the getActualMaximum
method in Calendar to retrieve the maximum day of a month.
import java.util.Calendar;
import java.util.Scanner;
public class EndDateOfMonth {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a date (YYYY-MM-DD): ");
String inputDate = scanner.nextLine();
String[] parts = inputDate.split("-");
int year = Integer.parseInt(parts[0]);
int month = Integer.parseInt(parts[1]) - 1; // Calendar month is 0-based
int day = Integer.parseInt(parts[2]);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
int endDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("End date of the month: " + endDay);
}
}
This program reads an input date in the format YYYY-MM-DD
from the user, splits it into its constituent parts, and sets the year, month, and day of the Calendar
object accordingly. It then uses the getActualMaximum
method to retrieve the maximum day of the month, which represents the end date of the month, and prints it to the console.
Note that this program assumes that the user inputs a valid date in the format YYYY-MM-DD
. You may want to add error checking to handle invalid input.