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 8 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. Checking a Weekend using LocalDate
The LocalDate.get(ChronoField.DAY_OF_WEEK)
method returns an integer value in the range of 1 to 7. Each integer value represents a different weekday.
1
represents Monday, and so on 6
represents Saturday and 7
represents Sunday.
By comparing the above integer value with days in DayOfWeek enum, we can determine if a date is a 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 a Weekend using Date and Calendar Classes
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 the week starts from Sunday (1) and ends on Saturday(7).
To check if a given Date is a weekday or weekend, we need to convert the java.util.Date instance to java.util.Calendar and perform the above-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 !!
Leave a Reply