📌  相关文章
📜  Java中的 WeekFields dayOfWeek() 方法及示例

📅  最后修改于: 2022-05-13 01:55:48.465000             🧑  作者: Mango

Java中的 WeekFields dayOfWeek() 方法及示例

WeekFields 类dayOfWeek()方法用于返回一个字段以根据此 WeekFields 访问星期几。例如,如果一周中的第一天是星期一,那么它将具有值 1,其他日期的范围从星期二为 2 到星期日为 7。

句法:

public TemporalField dayOfWeek()

参数:此方法不接受任何内容。

返回值:此方法返回一个字段,该字段提供对具有本地化编号的星期几的访问,而不是 null。

下面的程序说明了 WeekFields.dayOfWeek() 方法:
方案一:

// Java program to demonstrate
// WeekFields.dayOfWeek() method
  
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalField;
import java.time.temporal.WeekFields;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create WeekFields
        WeekFields weekFields
            = WeekFields.of(DayOfWeek.MONDAY, 1);
  
        // apply dayOfWeek()
        TemporalField dayOfWeek
            = weekFields.dayOfWeek();
  
        // create a LocalDate
        LocalDate day = LocalDate.of(2021, 12, 21);
  
        // get day of week for localdate
        int dow = day.get(dayOfWeek);
  
        // print results
        System.out.println("day of week for "
                           + day + " :" + dow);
    }
}
输出:
day of week for 2021-12-21 :2

方案二:

// Java program to demonstrate
// WeekFields.dayOfWeek() method
  
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalField;
import java.time.temporal.WeekFields;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create WeekFields
        WeekFields weekFields
            = WeekFields.of(DayOfWeek.SUNDAY, 1);
  
        // apply dayOfWeek()
        TemporalField dayOfWeek
            = weekFields.dayOfWeek();
  
        // create a LocalDate
        LocalDate day
            = LocalDate.of(2018, 05, 31);
  
        // get day of week for localdate
        int dow = day.get(dayOfWeek);
  
        // print results
        System.out.println("day of week for "
                           + day + " :" + dow);
    }
}
输出:
day of week for 2018-05-31 :5

参考资料:https: Java/time/temporal/WeekFields.html#dayOfWeek()