Java中的 WeekFields weekOfMonth() 方法及示例
WeekFields 类的weekOfMonth()方法用于返回字段以根据此 WeekFields 访问月份中的星期几。
例如:
- 如果该月的第一天是星期一,则第一周从 1 日开始,并且没有第 0 周
- 如果该月的第 2 天是星期一,则第一周从第 2 天开始,第 1 天在第 0 周
- 如果该月的第 4 天是星期一,则第一周从第 4 天开始,第 1 到第 3 天在第 0 周
- 如果每月的第 5 天是星期一,则第二周从 5 日开始,第 1 至 4 日为第一周
此字段可用于任何日历系统。
句法:
public TemporalField weekOfMonth()
参数:此方法不接受任何内容。
返回值:此方法返回一个提供对基于周的年份的访问的字段,而不是 null。
下面的程序说明了 WeekFields.weekOfMonth() 方法:
方案一:
// 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
方案二:
// 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: Java/time/temporal/WeekFields.html#weekOfMonth()