最近在做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));// String startTime = "2023-09-27 00:00:00" ;
// String endTime = "2023-09-27 00:00:10" ;
// String costTime = dateDiff(startTime,endTime);
// System.out.println(costTime );
} }
标签:00,Java,String,程序运行,SimpleDateFormat,startTime,new,秒数,endTime From: https://www.cnblogs.com/yeyuzhuanjia/p/17733003.html