Java Program To Find Day Of The Week For A Given Date
Chapter:
Date and Time
Last Updated:
10-08-2023 15:58:06 UTC
Program:
/* ............... START ............... */
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DayOfWeekFinder {
public static void main(String[] args) {
String inputDate = "2023-08-10"; // Replace with your desired date in yyyy-MM-dd format
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.parse(inputDate, dateFormatter);
DayOfWeek dayOfWeek = date.getDayOfWeek();
String dayOfWeekName = dayOfWeek.toString();
System.out.println("The day of the week for " + inputDate + " is " + dayOfWeekName);
}
}
/* ............... END ............... */
Notes:
-
Replace the inputDate variable with the date you want to find the day of the week for in the format "yyyy-MM-dd". The program will then parse the input date, determine the day of the week using the getDayOfWeek() method, and print the result.
- Make sure you have the correct Java environment set up to compile and run the program. The java.time package was introduced in Java 8, so make sure you're using a version of Java that supports it.
- DateTimeFormatter object is created to specify the format of the input date. "yyyy-MM-dd" corresponds to the year, month, and day format.
- The LocalDate.parse() method is used to parse the input date using the specified format. The result is stored in a LocalDate object named date.
- The getDayOfWeek() method is used to obtain the day of the week as a DayOfWeek enum value from the parsed date. The day's name is then converted to a string representation.
- Finally, the program prints out the result by combining the input date and the determined day of the week.