How to check whether the given date represents weekend in Java


At first, display the current date:

LocalDate date = LocalDate.now();

Now, get the day of week from the above Date (current date):

DayOfWeek day = DayOfWeek.of(date.get(ChronoField.DAY_OF_WEEK));

On the basis of the above result, use SWITCH to check for the current day. If the day is SATURDAY/SUNDAY, then it’s Weekend.

Example

import java.time.DayOfWeek;
import java.time.temporal.ChronoField;
import java.time.LocalDate;
public class Demo {
   public static void main(String[] argv) {
      LocalDate date = LocalDate.now();
      DayOfWeek day = DayOfWeek.of(date.get(ChronoField.DAY_OF_WEEK));
      switch (day) {
         case SATURDAY:
            System.out.println("Weekend - Saturday");
         case SUNDAY:
            System.out.println("Weekend - Sunday");
         default:
            System.out.println("Not a Weekend");
      }
   }
}

Output

Not a Weekend

Updated on: 30-Jul-2019

757 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements