📜  Java8 Duration类

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

Java Duration类

Java Duration类用于以秒和纳秒为单位测量时间。它继承了Object类并实现Comparable接口。

Java Duration类声明

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

public final class Duration extends Object 
implements TemporalAmount, Comparable, Serializable

Java持续时间的方法

Method Description
Temporal addTo(Temporal temporal) It is used to add this duration to the specified temporal object.
static Duration between(Temporal startInclusive, Temporal endExclusive) It is used to obtain a Duration representing the duration between two temporal objects.
long get(TemporalUnit unit) It is used to get the value of the requested unit.
boolean isNegative() It is used to check if this duration is negative, excluding zero.
boolean isZero() It is used to check if this duration is zero length.
Duration minus(Duration duration) It is used to return a copy of this duration with the specified duration subtracted.
Duration plus(Duration duration) It is used to return a copy of this duration with the specified duration added.

Java持续时间示例:get()

import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationExample1 {
  public static void main(String[] args) {
    Duration d = Duration.between(LocalTime.NOON,LocalTime.MAX);
    System.out.println(d.get(ChronoUnit.SECONDS));  
  }
}

输出:

43199

Java持续时间示例:isNegative()

import java.time.*;
public class DurationExample2 {
  public static void main(String[] args) {
  Duration d1 = Duration.between(LocalTime.MAX,LocalTime.NOON);
  System.out.println(d1.isNegative());
  Duration d2 = Duration.between(LocalTime.NOON,LocalTime.MAX);
              System.out.println(d2.isNegative());    
  }
}

输出:

true
false

Java持续时间示例:between()

import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationExample3 {
  public static void main(String[] args) {
    Duration d = Duration.between(LocalTime.NOON,LocalTime.MAX);
    System.out.println(d.get(ChronoUnit.SECONDS));  
  }
}

输出:

43199

Java持续时间示例:minus()

import java.time.*;
public class DurationExample4 {
  public static void main(String[] args) {
    Duration d1 = Duration.between(LocalTime.NOON,LocalTime.MAX);
    System.out.println(d1.getSeconds());
    Duration d2 = d1.minus(d1);
    System.out.println(d2.getSeconds());
  }
}

输出:

43199
0

Java持续时间示例:plus()

import java.time.*;
public class DurationExample5 {
  public static void main(String[] args) {
    Duration d1 = Duration.between(LocalTime.NOON,LocalTime.MAX);
    System.out.println(d1.getSeconds());
    Duration d2 = d1.plus(d1);
    System.out.println(d2.getSeconds());
  }
}

输出:

43199
86399