Java 8 – Check if Date or LocalDate is Weekend

Learn to check if a given date is a weekend in Java. We will learn to check using java.util.Date as well as java.time.LocalDate classes.

In the given examples, we are assuming that a weekend is either Saturday or Sunday. The rest five days of the week are weekdays.

1. java.time.LocalDate – Java 8

The LocalDate.get(ChronoField.DAY_OF_WEEK) method returns an integer value in range of 1 to 7. Each integer value represents a different week day.

1 represents Monday, and so on 6 represents Saturday and 7 represents Sunday.

By comparing above integer value with days in DayOfWeek enum, we can determine if a date is weekday or weekend.

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoField;

public class Main 
{
    public static void main(final String[] args) 
    {
        LocalDate today = LocalDate.now();
        System.out.println("Is weekend : " + isWeekend(today));

        LocalDate someDate = LocalDate.of(2021, 1, 2); // 2nd-Jan-2021
        System.out.println("Is weekend : " + isWeekend(someDate));
    }

    public static boolean isWeekend(final LocalDate ld) 
    {
        DayOfWeek day = DayOfWeek.of(ld.get(ChronoField.DAY_OF_WEEK));
        return day == DayOfWeek.SUNDAY || day == DayOfWeek.SATURDAY;
    }
}

2. Checking Weekend in Java 7

Similar to the new Java 8 date-time API, Java 7 also had Calendar.get(Calendar.DAY_OF_WEEK) method which returned an integer value representing a day in the week.

The integer value ranges from 1 to 7 and week starts from Sunday (1) and ends at Saturday (7).

To check if a given Date is a weekday of weekend, we need to convert the java.util.Date instance to java.util.Calendar and perform the aobe mentioned comparison.

import java.util.Calendar;
import java.util.Date;

public class Main 
{
    public static void main(final String[] args) 
    {
        Date today = new Date();
        System.out.println("Is weekend : " + isWeekend(today));

        @SuppressWarnings("deprecation")
        Date someDate = new Date(2021, 0, 2);
        System.out.println("Is weekend : " + isWeekend(someDate));
    }

    public static boolean isWeekend(final Date d) 
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);

        int day = cal.get(Calendar.DAY_OF_WEEK);
        return day == Calendar.SATURDAY || day == Calendar.SUNDAY;
    }
}

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.