📌  相关文章
📜  Java中的 ZoneOffset adjustInto(Temporal) 方法及示例

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

Java中的 ZoneOffset adjustInto(Temporal) 方法及示例

Java.time 包ZoneOffset 类adjustInto(Temporal)方法用于获取一个调整后的Temporal 实例,该实例调整到该ZoneOffset 实例中。该方法以 Temporal 实例为参数,返回一个 Temporal 实例,即调整后的实例。

句法:

public Temporal adjustInto(Temporal temporalInstance)

参数:此方法接受一个参数temporalInstance ,该参数是要调整的 Temporal 实例。

返回值:此方法返回一个Temporal 实例,它是此 Temporal 实例的调整值。

异常:此方法引发以下异常:

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

下面的示例说明了 ZoneOffset.adjustInto() 方法:

示例 1:

// Java code to illustrate adjustInto() method
  
import java.time.temporal.*;
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the Temporal instance
        ZonedDateTime temporalInstance
            = ZonedDateTime.now();
  
        System.out.println("Original Temporal instance: "
                           + temporalInstance);
  
        // Get the ZoneOffset
        ZoneOffset zoneOffset
            = ZoneOffset.ofHours(5);
  
        // Using adjustInto() method
        ZonedDateTime adjustedTemporal
            = (ZonedDateTime)zoneOffset
                  .adjustInto(temporalInstance);
  
        System.out.println("Adjusted Temporal instance: "
                           + adjustedTemporal);
    }
}
输出:
Original Temporal instance: 2018-12-11T09:44:14.373Z[Etc/UTC]
Adjusted Temporal instance: 2018-12-11T09:44:14.373Z[Etc/UTC]

示例 2:

// Java code to illustrate adjustInto() method
  
import java.time.temporal.*;
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the Temporal instance
        OffsetDateTime temporalInstance
            = OffsetDateTime.now();
  
        System.out.println("Original Temporal instance: "
                           + temporalInstance);
  
        // Get the ZoneOffset
        ZoneOffset zoneOffset
            = ZoneOffset.ofHours(5);
  
        // Using adjustInto() method
        Temporal adjustedTemporal
            = zoneOffset
                  .adjustInto(temporalInstance);
  
        System.out.println("Adjusted Temporal instance: "
                           + adjustedTemporal);
    }
}
输出:
Original Temporal instance: 2018-12-11T09:44:16.893Z
Adjusted Temporal instance: 2018-12-11T09:44:16.893+05:00

参考: Oracle 文档