Java 中的 zone offset getLong(temporal field)方法,示例

原文:https://www . geesforgeks . org/zone offset-getlongtemporalfield-method-in-Java-with-examples/

java.time 包ZoneOffset 类getLong(TemporalField) 方法用于从这个 ZoneOffset 实例中获取指定的 TemporalField 的值。此方法将临时字段作为参数,并返回该字段的长值。

语法:

public long getLong(TemporalField temporalField)

参数:该方法接受一个参数临时字段,该参数是该区域偏移实例所必需的。

返回值:这个方法返回一个长值,它是作为参数传递给这个 ZoneOffset 实例的临时字段的字段值。

异常:如果无法获取字段的值或该值超出字段的有效值范围

  • **This method throws:

    • Date and time exception: If this field is not supported or the value range is beyond int
    • , this method throws an exception: If there is a number overflow**

以下示例说明了 ZoneOffset.getLong()方法:

例 1:

// Java code to illustrate getLong() method

import java.time.*;
import java.time.temporal.*;

public class GFG {
    public static void main(String[] args)
    {

        // Get the ZoneOffset instance
        ZoneOffset zoneOffset
            = ZoneOffset.of("+05:30");
        System.out.println("ZoneOffset: "
                           + zoneOffset);

        // Using getLong() method
        System.out.println("Second value: "
                           + zoneOffset.getLong(ChronoField.OFFSET_SECONDS));
    }
}

输出:

ZoneOffset: +05:30
Second value: 19800

示例 2: 显示日期时间异常

// Java code to illustrate getLong() method

import java.time.*;
import java.time.temporal.*;

public class GFG {
    public static void main(String[] args)
    {

        try {
            // Get the ZoneOffset instance
            ZoneOffset zoneOffset
                = ZoneOffset.ofHours(25);
            System.out.println("ZoneOffset: "
                               + zoneOffset);

            // Using getLong() method
            System.out.println("Second value: "
                               + zoneOffset.getLong(ChronoField.OFFSET_SECONDS));
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出:

java.time.DateTimeException: Zone offset hours not in valid range: value 25 is not in the range -18 to 18

参考: 甲骨文文档