📌  相关文章
📜  Java中的 TemporalAdjusters previousOrSame() 方法和示例

📅  最后修改于: 2022-05-13 01:55:18.082000             🧑  作者: Mango

Java中的 TemporalAdjusters previousOrSame() 方法和示例

TemporalAdjusters 类previousOrSame(DayOfWeek)方法用于返回前一周或同一天的 TemporalAdjuster 对象,该对象可用于获取新的 Date 对象,该对象是具有相同匹配日期的前一个或同一日期星期作为参数从应用此 TempotralAdjuster 的任何 Date 对象传递。

句法:

public static TemporalAdjuster
       previousOrSame(DayOfWeek dayOfWeek)

参数:此方法接受dayOfWeek可用于获取新的 Date 对象,该对象是前一个或相同的日期,具有与传递的相同匹配的星期几。它不应该为空。

返回值:此方法返回前一周或同一天的 TemporalAdjuster 对象。

下面的程序说明了 TemporalAdjusters.previousOrSame() 方法:
方案一:

// Java program to demonstrate
// TemporalAdjusters.previousOrSame()
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get TemporalAdjuster with the
        // previousOrSame() of month adjuster
        TemporalAdjuster temporalAdjuster
            = TemporalAdjusters
                  .previousOrSame(
                      DayOfWeek.FRIDAY);
  
        // Using adjuster for local date-time
        LocalDate localDate
            = LocalDate.of(2020, 10, 30);
        LocalDate previousOrSameDOW
            = localDate.with(temporalAdjuster);
  
        // Print
        System.out.println(
            "Previous or same date "
            + "having FRIDAY for localdate "
            + localDate + " is: "
            + previousOrSameDOW);
    }
}
输出:
Previous or same date having FRIDAY for localdate 2020-10-30 is: 2020-10-30

方案二:

// Java program to demonstrate
// TemporalAdjusters previousOrSame() method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get TemporalAdjuster with the
        // previousOrSame() day of week adjuster
        TemporalAdjuster temporalAdjuster
            = TemporalAdjusters
                  .previousOrSame(
                      DayOfWeek.THURSDAY);
  
        // Using adjuster for local date time
        LocalDate localDate
            = LocalDate.of(2018, 02, 23);
        LocalDate previousOrSameDOW
            = localDate.with(temporalAdjuster);
  
        // Print
        System.out.println(
            "Previous or same date "
            + "having THURSDAY for localdate "
            + localDate + " is: "
            + previousOrSameDOW);
    }
}
输出:
Previous or same date having THURSDAY for localdate 2018-02-23 is: 2018-02-22

参考资料:https: Java Java.time.DayOfWeek)