📌  相关文章
📜  带有示例的Java中的 ChronoLocalDateTime with(TemporalAdjuster) 方法

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

带有示例的Java中的 ChronoLocalDateTime with(TemporalAdjuster) 方法

ChronoLocalDateTime接口的with(TemporalAdjusteradjuster)方法用于使用 TemporalAdjuster 调整此日期时间,调整后返回调整后的日期时间副本。使用指定的调整器策略对象进行调整。这个 ChronoLocalDateTime 实例是不可变的,不受此方法调用的影响。一个简单的调整器用于设置其中一个字段,例如年份字段,一个更复杂的调整器可能会将时间设置为一年中的最后一天。

句法:

default ChronoLocalDateTime with(TemporalAdjuster adjuster)

参数:此方法接受调节器作为要使用的调节器的参数。

返回值:此方法在此基础上返回一个 ChronoLocalDateTime 并进行调整。

异常:此方法抛出以下异常:

  • DateTimeException – 如果无法进行调整。
  • ArithmeticException – 如果发生数字溢出。

下面的程序说明了 with() 方法:

方案一:

// Java program to demonstrate
// ChronoLocalDateTime.with() method
  
import java.time.*;
import java.time.chrono.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create ChronoLocalDateTime object
        ChronoLocalDateTime time
            = LocalDateTime
                  .parse("2019-12-31T19:15:30");
  
        // print instance
        System.out.println("ChronoLocalDateTime before"
                           + " adjustment: "
                           + time);
  
        // apply with method of ChronoLocalDateTime
        ChronoLocalDateTime updatedlocal
            = time.with(Month.OCTOBER)
                  .with(TemporalAdjusters
                            .firstDayOfMonth());
  
        // print instance
        System.out.println("ChronoLocalDateTime after"
                           + " adjustment: "
                           + updatedlocal);
    }
}
输出:
ChronoLocalDateTime before adjustment: 2019-12-31T19:15:30
ChronoLocalDateTime after adjustment: 2019-10-01T19:15:30

方案二:

// Java program to demonstrate
// ChronoLocalDateTime.with() method
  
import java.time.*;
import java.time.chrono.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create ChronoLocalDateTime object
        ChronoLocalDateTime time
            = LocalDateTime
                  .parse("2018-10-25T23:12:31.123");
  
        // print instance
        System.out.println("ChronoLocalDateTime before"
                           + " adjustment: "
                           + time);
  
        // apply with method of ChronoLocalDateTime
        ChronoLocalDateTime updatedlocal
            = time.with(Month.JANUARY)
                  .with(TemporalAdjusters
                            .firstDayOfMonth());
  
        // print instance
        System.out.println("ChronoLocalDateTime after"
                           + " adjustment: "
                           + updatedlocal);
    }
}
输出:
ChronoLocalDateTime before adjustment: 2018-10-25T23:12:31.123
ChronoLocalDateTime after adjustment: 2018-01-01T23:12:31.123

参考: https://docs.oracle.com/javase/9/docs/api/ Java/time/chrono/ChronoLocalDateTime.html#with-java.time.temporal.TemporalAdjuster-