当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java WeekFields dayOfWeek()用法及代码示例


WeekFields类的dayOfWeek()方法用于返回一个字段,以基于此WeekFields访问星期几。例如,如果第一个day-of-week是星期一,那么它将具有值1,其他日期从星期二为2到星期日为7。

用法:

public TemporalField dayOfWeek()

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


返回值:此方法返回一个字段,该字段提供对day-of-week的访问,该字段具有本地化编号,不为null。

以下示例程序旨在说明WeekFields.dayOfWeek()方法:
程序1:

// 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

程序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://docs.oracle.com/javase/10/docs/api/java/time/temporal/WeekFields.html#dayOfWeek()



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 WeekFields dayOfWeek() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。