Java OffsetDateTime getLong()方法及示例

来源:这里教程网 时间:2026-02-17 20:59:56 作者:

Java OffsetDateTime getLong()方法及示例

Java中OffsetDateTime类的 getLong() 方法从这个日期时间中获取指定字段的值,作为一个long。

语法:

public long getLong(TemporalField field)

参数: 该方法接受一个单一的参数 field ,指定要获得的字段,不为空。

返回值: 它返回该字段的值。

异常 :该函数抛出三种异常,描述如下。

DateTimeException :如果不能获得字段的值,或者该值超出了该字段的有效值范围,就会抛出这种异常。UnsupportedTemporalTypeException :如果该字段不被支持或者数值范围超过了一个长值,就会抛出这个异常。ArithmeticException :如果发生数字溢出,将被抛出。

下面的程序说明了getLong()方法。

程序1 :

// Java program to demonstrate the getLong() methodimport java.time.OffsetDateTime;import java.time.temporal.ChronoField;  public class GFG {    public static void main(String[] args)    {          // parses a date        OffsetDateTime date = OffsetDateTime.parse("2018-12-03T12:30:30+01:00");          // Prints the value of the specified        // field from this date-time as an long.        System.out.println(date.getLong(ChronoField.CLOCK_HOUR_OF_DAY));    }}

输出。

12

程序2 :

// Java program to demonstrate the getDayOfYear() method// exceptions  import java.time.OffsetDateTime;import java.time.temporal.ChronoField;  public class GFG {    public static void main(String[] args)    {        try {            // parses a date            OffsetDateTime date = OffsetDateTime.parse("2018-24-03T12:30:30+01:00");              // Prints the value of the specified            // field from this date-time as an long.            System.out.println(date.getLong(ChronoField.CLOCK_HOUR_OF_DAY));        }        catch (Exception e) {            System.out.println(e);        }    }}

输出。

java.time.format.DateTimeParseException: Text '2018-24-03T12:30:30+01:00' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 24

参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/temporal/TemporalField.html

相关推荐