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


Java WeekFields weekOfMonth()用法及代碼示例


WeekFields類的weekOfMonth()方法用於返回字段,以基於此WeekFields訪問每月的星期。例如:

  • 如果每月的第一天是星期一,則第一周從第一天開始,沒有零周
  • 如果每月的第二天是星期一,則第一周在第二天開始,第一天在零周
  • 如果每月的第4天是星期一,則第1周從第4周開始,第1至第3周在零周開始
  • 如果每月的第5天是星期一,則第二周從第5周開始,而第1至第4周在第一周

該字段可用於任何日曆係統。

用法:


public TemporalField weekOfMonth()

參數:此方法不接受任何內容。

返回值:此方法返回一個提供對week-based-year的訪問權限的字段,而不是null。

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

// Java program to demonstrate 
// WeekFields.weekOfMonth() 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 weekOfMonth() 
        TemporalField weekOfMonth 
            = weekFields.weekOfMonth(); 
  
        // create a LocalDate 
        LocalDate day 
            = LocalDate.of(2021, 12, 21); 
  
        // get week of month for localdate 
        int wom = day.get(weekOfMonth); 
  
        // print results 
        System.out.println("week of month for "
                           + day + ":" + wom); 
    } 
}
輸出:
week of month for 2021-12-21:4

程序2:

// Java program to demonstrate 
// WeekFields.weekOfMonth() 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 weekOfMonth() 
        TemporalField weekOfMonth 
            = weekFields.weekOfMonth(); 
  
        // create a LocalDate 
        LocalDate day = LocalDate.of(2020, 01, 10); 
  
        // get week of month for localDate 
        int wom = day.get(weekOfMonth); 
  
        // print results 
        System.out.println("week of month for "
                           + day + ":" + wom); 
    } 
}
輸出:
week of month for 2020-01-10:2

參考:https://docs.oracle.com/javase/10/docs/api/java/time/temporal/WeekFields.html#weekOfMonth()



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 WeekFields weekOfMonth() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。