Java中的 DayOfWeek adjustInto() 方法及示例
Java .time.DayOfWeek的adjustInto()方法是Java中的一个内置函数,它接受一个指定日期的 Temporal 对象并返回一个与输入相同的可观察类型的新 Temporal 对象,其中星期更改为与指定的 DayOfWeek 常量相同。请注意,此方法在周一至周日一周内向前或向后调整。
方法声明:
public Temporal adjustInto(Temporal temporal)
句法:
Temporal newLocalDate = DayOfWeek.ANYWEEKDAY.adjustInto(Temporal temporal)
参数:此方法将时间作为参数,其中:
返回值:该函数返回一个调整后的 Temporal 对象,它是根据指定的星期几调整的日期。
下面的程序说明了上述方法:
方案一:
import java.time.*;
import java.time.DayOfWeek;
import java.time.temporal.Temporal;
class DayOfWeekExample {
public static void main(String[] args)
{
// Set a Local Date whose day is found
LocalDate localDate1
= LocalDate.of(1947, Month.AUGUST, 15);
// Find the day from the Local Date
DayOfWeek dayOfWeek1
= DayOfWeek.from(localDate1);
// Printing the Local Date
System.out.println(localDate1
+ " which is "
+ dayOfWeek1.name());
// Adjust the Date to Monday from Friday
Temporal localDate2
= DayOfWeek.MONDAY
.adjustInto(localDate1);
// Find the day from the new Local date
DayOfWeek dayOfWeek2
= DayOfWeek.from(localDate2);
// Printing the new Local Date
System.out.println(localDate2
+ " which is "
+ dayOfWeek2.name());
}
}
输出:
1947-08-15 which is FRIDAY
1947-08-11 which is MONDAY
方案二:
import java.time.*;
import java.time.DayOfWeek;
import java.time.temporal.Temporal;
class DayOfWeekExample {
public static void main(String[] args)
{
// Set a Local Date whose day is found
LocalDate localDate1
= LocalDate.of(2019, Month.MARCH, 18);
// Find the day from the Local Date
DayOfWeek dayOfWeek1
= DayOfWeek.from(localDate1);
// Printing the Local Date
System.out.println(localDate1
+ " which is "
+ dayOfWeek1.name());
// Adjust the Date to Wednesday from Monday
Temporal localDate2
= DayOfWeek.WEDNESDAY
.adjustInto(localDate1);
// Find the day from the new Local date
DayOfWeek dayOfWeek2
= DayOfWeek.from(localDate2);
// Printing the new Local Date
System.out.println(localDate2
+ " which is "
+ dayOfWeek2.name());
}
}
输出:
2019-03-18 which is MONDAY
2019-03-20 which is WEDNESDAY
参考: https: Java/time/DayOfWeek.html#adjustInto-java.time.temporal.Temporal-