📜  Java8 OffsetTime类

📅  最后修改于: 2020-10-01 06:37:25             🧑  作者: Mango

Java OffsetTime类

Java OffsetTime类是一个不变的日期时间对象,它代表一个时间,通常被视为小时,分钟,秒的偏移量。它继承了Object类并实现Comparable接口。

Java OffsetTime类声明

让我们来看一下java.time.OffsetTime类的声明。

public final class OffsetTime extends Object 
implements Temporal, TemporalAdjuster, Comparable, Serializable

Java OffsetTime的方法

Method Description
String format(DateTimeFormatter formatter) It is used to format this time using the specified formatter.
int get(TemporalField field) It is used to get the value of the specified field from this time as an int.
int getHour() It is used to get the hour-of-day field.
int getMinute() It is used to get the minute-of-hour field.
int getSecond() It is used to get the second-of-minute field.
static OffsetTime now() It is used to obtain the current time from the system clock in the default time-zone.
static OffsetTime of(LocalTime time, ZoneOffset offset) It is used to obtain an instance of OffsetTime from a local time and an offset.
ValueRange range(TemporalField field) It is used to get the range of valid values for the specified field.
VLocalTime toLocalTime() It is used to get the LocalTime part of this date-time.

Java OffsetTime类示例

import java.time.OffsetTime;
import java.time.temporal.ChronoField;
public class OffsetTimeExample1 {
  public static void main(String[] args) {
    OffsetTime offset = OffsetTime.now();
    int h = offset.get(ChronoField.HOUR_OF_DAY);
    System.out.println(h);
    int m = offset.get(ChronoField.MINUTE_OF_DAY);
    System.out.println(m);
    int s = offset.get(ChronoField.SECOND_OF_DAY);
    System.out.println(s);
  }
}

输出:

16
970
58224

Java OffsetTime类示例:getHour()

import java.time.OffsetTime;
public class OffsetTimeExample2 {
  public static void main(String[] args) {
    OffsetTime offset = OffsetTime.now();
    int h = offset.getHour();
    System.out.println(h+ " hour");
  }
}

输出:

15 hour

Java OffsetTime类示例:getMinute()

import java.time.OffsetTime;
public class OffsetTimeExample3 {
  public static void main(String[] args) {
    OffsetTime offset = OffsetTime.now();
    int m = offset.getMinute();
    System.out.println(m+ " minute");
  }
}

输出:

24 minute

Java OffsetTime类示例:getSecond()

import java.time.OffsetTime;
public class OffsetTimeExample4 {
  public static void main(String[] args) {
    OffsetTime offset = OffsetTime.now();
    int s = offset.getSecond();
    System.out.println(s+ " second");
  }
}

输出:

8 second