如何使用 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
广告