Java程序获取两个时间点之间的毫秒数


在本文中,我们将演示如何使用ChronoUnit 类计算两个Instant 对象之间以毫秒为单位的差值。它展示了如何在java.time 包中使用基于时间类,特别侧重于创建和操作时间点以及计算它们之间的时间差。

ChronoUnit: 一组标准的日期和时间单位,允许您操作日期、时间和日期时间。这些单位,例如年、月和日,旨在适用于各种日历系统,尽管具体规则可能略有不同。您还可以通过实现TemporalUnit 接口来扩展这些单位。

问题陈述

使用 Java 的 Instant、Duration 和 ChronoUnit 类计算两个特定时间点之间以毫秒为单位的时间差

输出

Milliseconds between two time instants = 18050000

获取两个时间点之间毫秒数的步骤

以下是获取两个时间点之间毫秒数的步骤:

  • java.time 包导入必要的类。
  • 创建初始时间点,使用Instant.now()捕获当前时间time1
  • 通过使用plus() 方法向 time1 添加 5 小时 50 秒来创建第二个时间点time2
  • 定义持续时间为 13 秒。
  • 将此持续时间添加到time1以获取新的时间点i
  • 使用ChronoUnit.MILLIS.between()查找time1time2之间以毫秒为单位的差值。
  • 打印结果

Java程序获取两个时间点之间的毫秒数

以下是获取两个时间点之间毫秒数的Java程序:

import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class Demo {
    public static void main(String[] args) {
        Instant time1 = Instant.now();
        Instant time2 = time1.plus(5, ChronoUnit.HOURS).plus(50, ChronoUnit.SECONDS);
        Duration duration = Duration.ofSeconds(13);
        Instant i = time1.plus(duration);
        System.out.println("Milliseconds between two time instants = " +
            ChronoUnit.MILLIS.between(time1, time2));
    }
}

输出

Milliseconds between two time instants = 18050000

代码解释

该程序从java.time 包导入类以处理时间点和持续时间。它首先使用Instant.now()创建一个表示当前时刻的时间点time1

首先,创建两个时间点:

Instant time1 = Instant.now();
Instant time2 = time1.plus(5, ChronoUnit.HOURS).plus(50, ChronoUnit.SECONDS);

然后,通过使用 Instant 类的plus()方法向time1添加 5 小时 50 秒来创建第二个时间点time2。定义一个长度为 13 秒的Duration 对象,然后将其添加到time1以创建另一个时间点i

Duration duration = Duration.ofSeconds(13);
Instant i = time1.plus(duration);
System.out.println("Milliseconds between two time instants = "+ChronoUnit.MILLIS.between(time1, time2));

为了确定time1time2之间以毫秒为单位的时间差,使用了ChronoUnit.MILLIS.between()方法。打印结果,显示两个时间点之间以毫秒为单位的总时间差。

更新于: 2024年8月12日

2K+ 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.