如何用Java检查给定的日期是否代表周末

首先,显示当前日期:

LocalDate date = LocalDate.now();

现在,从上述日期(当前日期)中获取星期几:

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

根据上述结果,使用SWITCH检查当天。如果一天是星期六/周日,则为周末。

示例

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");
      }
   }
}

输出结果

Not a Weekend