Java code to check if date is weekend
Chapter:
Date and Time
Last Updated:
29-06-2023 04:45:26 UTC
Program:
/* ............... START ............... */
import java.time.DayOfWeek;
import java.time.LocalDate;
public class WeekendChecker {
public static void main(String[] args) {
LocalDate dateToCheck = LocalDate.of(2023, 6, 30);
if (isWeekend(dateToCheck)) {
System.out.println(dateToCheck + " is a weekend day.");
} else {
System.out.println(dateToCheck + " is not a weekend day.");
}
}
public static boolean isWeekend(LocalDate date) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
return dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY;
}
}
/* ............... END ............... */
Output
2023-06-30 is not a weekend day.
In this example, the code checks whether June 30, 2023, is a weekend day.
Since June 30, 2023, falls on a Friday, the output indicates that it is not a weekend day.
Notes:
-
In this code, the isWeekend() method takes a LocalDate object as input and checks if its corresponding DayOfWeek is either Saturday or Sunday. If it is, the method returns true, indicating that the date is a weekend. Otherwise, it returns false.
- You can change the dateToCheck value to any date you want to verify, and the code will output whether it is a weekend day or not.