Write a Java program to print the first and last date of a given month. In this Java program example, we will see how to print the first and last date of a month.
Sample Input
Enter the current date of the month for example 17/03/2022
Sample Output
First date: 01/03/2022
Last date: 31/03/2022
Algorithm to find first and last date of a month
- Take the current date input in the string and split the string “/”.
- Create two objects first for the print first date and another for the last date.
- Create an object and call the method that is Calendar.getInstance();.
- Convert string in integers and print appropriate first and last date.
Java program to print first and last date of a month
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
public class Date {
public static void main(String[] args) {
String currentDate = "17/03/2022";//enter date here
String[] splt = currentDate.split("/");
LocalDate Fdate = LocalDate.of(Integer.parseInt(splt[2]), Integer.parseInt(splt[1]), Integer.parseInt(splt[0]))
.plusDays(-(Integer.parseInt(splt[0]) - 1));
System.out.println("first Date: " + Fdate);
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(splt[2]), (Integer.parseInt(splt[1])) - 1, Integer.parseInt(splt[0]));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
SimpleDateFormat ldate1 = new SimpleDateFormat("yyyy-MM-dd");
String ldate = ldate1.format(cal.getTime());
System.out.println("Last Date: " + ldate);
}
}
Explanation of this Java program
Step 1: Start.
Step 2: Create a class Date and main method.
Step 3: Take input in String and split it.
Step 4: Create an object and convert a string into integers and call plus method to add or subtract the days from the current date and print the first and last date.
Step 5: Call Calendar.getInstance() method for the current date to print the last date of the month.
Step 6: Same as step 4.
Step 7: Print the last date of the month.
Step 8: End.
Output
first Date: 2022-03-01
Last Date: 2022-03-31
In this way, we learned how to write a Java program to print the first and last date of a month.