Java | 判断 两个 Date 相差多少时间

王先生
2024-07-08 / 0 评论 / 4 阅读 / 正在检测是否收录...

以下代码只返回相差秒数的"分钟部分",如果想得到总秒数,应该这样计算:

long diffSeconds = diff / 1000; 

旧版的java.util.Date

import java.util.Date;
import java.text.SimpleDateFormat;

public class Main {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = sdf.parse("2020-01-01 00:00:00");
        Date date2 = sdf.parse("2020-01-02 00:00:00");

        long diff = date2.getTime() - date1.getTime();
        long diffSeconds = diff / 1000 % 60;
        System.out.println("相差秒数: " + diffSeconds);
    }
}

新版本 Java

import java.time.LocalDateTime;
import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        // 创建两个 LocalDateTime 对象
        LocalDateTime dateTime1 = LocalDateTime.of(2020, 1, 1, 0, 0);
        LocalDateTime dateTime2 = LocalDateTime.now();

        // 使用 Duration.between() 方法计算两个时间点之间的时间差
        Duration duration = Duration.between(dateTime1, dateTime2);

        // 输出相差的秒数
        long seconds = duration.getSeconds();
        System.out.println("相差秒数: " + seconds);
    }
}

评论 (0)

取消