Java-统计程序运行的时长(计算两个时间相差的秒数)

发布时间 2023-09-27 16:28:09作者: 业余砖家

最近在做Hbase的查询性能验证,需要统计查询的执行时长,所以需要统计开始时间和结束时间的时间差。

下面是使用SimpleDateFormat和Date计算时间差(相差秒数)的程序示例,仅供参考。

package com.sgcc;

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

public class MyTest {

    public static String dateDiff(String startTime, String endTime) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long diff;
        try {
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        long diffSeconds = diff / 1000;
        return  diffSeconds + "秒";
    }

    public static void main(String[] args) {

        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = sdf.format(new Date());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String endTime = sdf.format(new Date());

        System.out.println(dateDiff(startTime,endTime));

    }
}