📜  Java8 DayOfWeek枚举

📅  最后修改于: 2020-10-01 06:42:20             🧑  作者: Mango

Java DayOfWeek枚举

在Java中,DayOfWeek是一个代表一周中7天的枚举。除了文本枚举名称外,每周的每一天都有一个int值。

Java DayOfWeek枚举声明

让我们看一下java.time.DayOfWeek的声明。

public enum DayOfWeek extends Enum implements TemporalAccessor, TemporalAdjuster

Java DayOfWeek的方法

Method Description
int get(TemporalField field) It is used to get the value of the specified field from this day-of-week as an int.
boolean isSupported(TemporalField field) It is used to check if the specified field is supported.
DayOfWeek minus(long days) It is used to return the day-of-week that is the specified number of days before this one.
DayOfWeek plus(long days) It is used to return the day-of-week that is the specified number of days after this one.
static DayOfWeek of(int dayOfWeek) It is used to obtain an instance of DayOfWeek from an int value.
static DayOfWeek[] values() It is used to return an array containing the constants of this enum type, in the order they are declared.

Java DayOfWeek示例:get()

import java.time.*;
import java.time.temporal.ChronoField;
public class DayOfWeekExample1 {
  public static void main(String[] args) {
    LocalDate localDate = LocalDate.of(2017, Month.JANUARY, 25);
    DayOfWeek dayOfWeek = DayOfWeek.from(localDate);
    System.out.println(dayOfWeek.get(ChronoField.DAY_OF_WEEK));
  }
}

输出:

3

Java DayOfWeek示例:of()

import java.time.DayOfWeek;
public class DayOfWeekExample2 {
  public static void main(String[] args) {
    DayOfWeek day = DayOfWeek.of(5);
    System.out.println(day.name());
    System.out.println(day.ordinal());
    System.out.println(day.getValue());
  }
}

输出:

FRIDAY
4
5

Java DayOfWeek示例:plus()

import java.time.*;
public class DayOfWeekExample3 {
  public static void main(String[] args) {
    LocalDate date = LocalDate.of(2017, Month.JANUARY, 31);
    DayOfWeek day = DayOfWeek.from(date);
    System.out.println(day.getValue());
    day = day.plus(3);
    System.out.println(day.getValue());
  }
}

输出:

2
5

Java DayOfWeek示例:minus()

import java.time.*;
public class DayOfWeekExample4 {
  public static void main(String[] args) {
    LocalDate date = LocalDate.of(2017, Month.JANUARY, 31);
    DayOfWeek day = DayOfWeek.from(date);
    System.out.println(day.getValue());
    day = day.minus(3);
    System.out.println(day.getValue());
  }
}

输出:

2
6