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