當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。