20230523 java.time.Duration

发布时间 2023-09-05 09:19:36作者: 流星<。)#)))≦

介绍

  • java.time.Duration
  • 类声明
@jdk.internal.ValueBased
public final class Duration implements TemporalAmount, Comparable<Duration>, Serializable
  • 两个时刻之间的时间量

  • 两个 Instant 之间的时长是 Duration

  • 在内部,秒数存储在一个 long 中 (seconds),而纳秒数存储在一个额外的 int 中 (nanos)

  • Duration 是基于时间的 TemporalAmount 实现,存储秒和纳秒,但使用其他基于 Duration 的单位(例如分钟、小时和固定的 24 小时制日)提供一些访问

    • Period 是一个基于日期的 TemporalAmount 实现,存储年月日。
  • 实现 TemporalAmount , 可以获取的时间单位:

    • NANOS
    • SECONDS
  • 支持换算为 日、小时、分钟、秒、毫秒、纳秒

API

常量

  • ZERO : PT0S
    • 0s

static

  • between

    • Duration between(Temporal startInclusive, Temporal endExclusive)
  • from

    • Duration from(TemporalAmount amount)
  • of

    • Duration of(long amount, TemporalUnit unit)
  • ofDays

    • Duration ofDays(long days)
  • ofHours

  • ofMinutes

  • ofSeconds

  • ofMillis

  • ofNanos

  • parse

    • toString

public

  • withSeconds

    • 返回具有指定秒数的该持续时间的副本
  • withNanos

    • 返回具有指定纳秒数的该持续时间的副本
  • getSeconds

  • getNano

  • isNegative

    • 是否负值
  • isZero

    • 是否 0
  • truncatedTo

    • 截断
  • toString

    • 返回持续时间的 ISO-8601 表示形式
    • 格式:PTnHnMnS
    • 例如 PT8H6M12.345S 表示8小时6分12.345秒

算数计算

  • minus

  • minusDays

  • minusHours

  • minusMillis

  • minusMinutes

  • minusNanos

  • minusSeconds

  • plus

  • plusDays

  • plusHours

  • plusMillis

  • plusMinutes

  • plusNanos

  • plusSeconds

  • negated

    • 取负值
  • abs

    • 取绝对值
  • multipliedBy

  • dividedBy

根据时间单位获取值

  • toDays
  • toDaysPart
  • toHours
  • toHoursPart
  • toMinutes
    • 换算为分钟单位
    • 例如 PT1H2M3S (1小时2分钟3秒钟) ,结果为 62
  • toMinutesPart
    • 得到分钟的部分值
    • 例如 PT1H2M3S (1小时2分钟3秒钟) ,结果为 2
  • toSeconds
  • toSecondsPart
  • toMillis
  • toMillisPart
  • toNanos
  • toNanosPart