Java DayOfWeek adjustInto()方法及示例

Java DayOfWeek adjustInto()方法及示例

java.time.DayOfWeekadjustInto() 方法是Java中的一个内置函数,它接收一个指定日期的Temporal对象,并返回一个与输入的可观察类型相同的新Temporal对象,其周天数被改为与指定的DayOfWeek常数相同。注意,这个方法可以在周一到周日的一周内向前或向后调整。

方法声明

 public Temporal adjustInto(Temporal temporal)

语法

 Temporal newLocalDate = DayOfWeek.ANYWEEKDAY.adjustInto(Temporal temporal)

参数: 该方法以temporal为参数,其中。

  • temporal – 是要调整的指定日期。
  • ANYWEEKDAY – 是指定的要调整的日期,例如,星期一,星期二,等等。
  • newLocalDate – 是修改后的日期。

返回值: 该函数返回一个调整后的时间对象,它是根据指定的星期几调整的日期。

下面的程序说明了上述方法:

程序1 :

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

程序2

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://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html#adjustInto-java.time.temporal.Temporal-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程