Java中的 TemporalAdjusters firstInMonth() 方法及示例
TemporalAdjusters 类的firstInMonth(DayOfWeek)方法用于返回一个 TemporalAdjuster 对象,该对象可用于获取一个新的 Date 对象,该对象是同月的第一个日期,具有与任何 Date 对象作为参数传递的相同匹配的 DayOfWeek应用此 TempotralAdjuster。
句法:
public static TemporalAdjuster
firstInMonth(DayOfWeek dayOfWeek)
参数:此方法接受dayOfWeek可用于获取新的 Date 对象,该对象是具有相同匹配 DayOfWeek 的同一月份的第一个日期。
返回值:此方法返回月份调整器中的第一个,不为空。
下面的程序说明了 TemporalAdjusters.firstInMonth() 方法:
方案一:
// Java program to demonstrate
// TemporalAdjusters.firstInMonth()
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// get TemporalAdjuster with
// the first in month adjuster
TemporalAdjuster temporalAdjuster
= TemporalAdjusters.firstInMonth(
DayOfWeek.SUNDAY);
// using adjuster for local date time
LocalDate localDate
= LocalDate.of(2023, 10, 11);
LocalDate firstInMonth
= localDate.with(temporalAdjuster);
// print
System.out.println(
"First date in month having"
+ " sunday for localdate "
+ localDate + " is: "
+ firstInMonth);
}
}
输出:
First date in month having sunday for localdate 2023-10-11 is: 2023-10-01
方案二:
// Java program to demonstrate
// TemporalAdjusters.firstInMonth() method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// get TemporalAdjuster with
// the first in month adjuster
TemporalAdjuster temporalAdjuster
= TemporalAdjusters.firstInMonth(
DayOfWeek.TUESDAY);
// using adjuster for local date-time
LocalDate localDate
= LocalDate.of(2023, 10, 11);
LocalDate firstInMonth
= localDate.with(temporalAdjuster);
// print
System.out.println(
"First date in a month having"
+ " TUESDAY for localdate "
+ localDate + " is: "
+ firstInMonth);
}
}
输出:
First date in a month having TUESDAY for localdate 2023-10-11 is: 2023-10-03
参考:https: Java Java.time.DayOfWeek)