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

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

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

WeekFields 类weekOfYear()方法用于根据此 WeekFields 返回一个字段以访问一年中的第几周。
例子:

  • 如果一年中的第一天是星期一,则第一周从第一天开始,并且没有零周
  • 如果一年中的第 2 天是星期一,则第一周从第 2 天开始,第 1 周在第 0 周
  • 如果一年中的第 4 天是星期一,则第一周从第 4 天开始,第 1 到第 3 天在第 0 周
  • 如果一年中的第 5 天是星期一,则第二周从 5 日开始,第 1 到第 4 天在第一周

此字段可用于任何日历系统。

句法:

public TemporalField weekOfYear()

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

返回值:此方法返回一个字段,该字段提供对一年中的一周的访问,而不是 null。

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

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

方案二:

// Java program to demonstrate
// WeekFields.weekOfYear() 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 weekOfYear()
        TemporalField weekOfYear
            = weekFields.weekOfYear();
  
        // create a LocalDate
        LocalDate day = LocalDate.of(2014, 10, 12);
  
        // get week of year for localdate
        int wow = day.get(weekOfYear);
  
        // print results
        System.out.println("Week of year for "
                           + day + " :" + wow);
    }
}
输出:
Week of year for 2014-10-12 :42

参考:https: Java/time/temporal/WeekFields.html#weekOfYear()