How to check whether the given date represents weekend in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 24-Apr-2019 12:06:42
Advertisements