How to check if a date is a weekend or not in Java
In this tutorial, we will learn how to check if a date is a weekend or not in Java. To do this we will use the LocalDate class in Java as shown below. We will use this as we are just dealing with date and not time. This class does not store time or time-zone.
Check if a date is a weekend or not in Java
Here are the steps you can follow:
- Initialize the LocalDate object
First, we have to Initialize the LocalDate object. To do this you can see the following code that is creating a LocalDate object and storing a specific date that is passed in the argument.//Initializing the LocalDate Object LocalDate date = LocalDate.of(year, month, dateOfMonth);
- Get the day of the week
Next, to check if the date is a Saturday or Sunday we will use the getDayOfWeek() method. This method will return the day of the date that is, from Monday to Sunday. Finally, we will compare it to Sunday and Saturday to get the result.//Check if the day is a Sunday or a Saturday if("SUNDAY".equals(date.getDayOfWeek().toString()) || "SATURDAY".equals(date.getDayOfWeek().toString())) { System.out.println("The date is a Weekend"); } else { System.out.println("The date is not a Weekend"); }
Java program to check if the given date is weekend or not
Now, here is a sample code that will get the date from user input. Next, it will store it in the LocalDate object so that we get the day of the week for that particular date. We will then compare the day of the week to Saturday or Sunday to print the right results.
import java.time.LocalDate; import java.util.Scanner; public class CheckWeekend { LocalDate date; //Getting the user input void getdata() { int year, month, dateOfMonth; Scanner sc = new Scanner(System.in); System.out.println("Enter the year:"); year = sc.nextInt(); System.out.println("Enter the Month:"); month = sc.nextInt(); System.out.println("Enter the Date Of the Month:"); dateOfMonth = sc.nextInt(); //Initializing the LocalDate Object date = LocalDate.of(year, month, dateOfMonth); } //Checking if the day is a Sunday or a Saturday void WeekedOrNot() { if("SUNDAY".equals(date.getDayOfWeek().toString()) || "SATURDAY".equals(date.getDayOfWeek().toString())) { System.out.println("The date is a Weekend"); } else { System.out.println("The date is not a Weekend"); } } public static void main(String args[]) { CheckWeekend CW = new CheckWeekend(); CW.getdata(); CW.WeekedOrNot(); } }
Output
Enter the year: 2019 Enter the Month: 01 Enter the Date Of the Month: 12 The date is a Weekend Enter the year: 2021 Enter the Month: 12 Enter the Date Of the Month: 15 The date is not a Weekend
Here is a topic that you can check out next: How to change the format of date from dd/mm/yyyy to mm/dd/yyyy in Java
Leave a Reply