📜  Java中的 WeekFields weekOfWeekBasedYear() 方法及示例

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

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

WeekFields 类weekOfWeekBasedYear()方法用于返回一个字段,以根据此 WeekFields 访问基于周的年份的周。
例子:

  • 如果一年中的第一天是星期一,则第一周从第一天开始
  • 如果一年中的第 2 天是星期一,则第一周从第 2 天开始,第 1 周在上一年的最后一周
  • 如果一年中的第 4 天是星期一,则第一周从第 4 天开始,第 1 到第 3 天是上一年的最后一周
  • 如果一年中的第 5 天是星期一,则第二周从 5 日开始,第 1 到第 4 天在第一周

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

句法:

public TemporalField weekOfWeekBasedYear()

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

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

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

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

方案二:

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

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