需要第三方依赖
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
详细代码
package com.zyp.test;
import org.apache.commons.lang3.time.StopWatch;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
/**
* @author syl
* @description 测试计时类
* @since 2022/7/13
*/
public class StopWatchTest {
private final static String PATTERN="yyyy-MM-dd HH:mm:ss";
public static void main(String[] args) throws InterruptedException {
//创建对象并开启计时
StopWatch watch=StopWatch.createStarted();
System.out.println("当前时间:"+longToString(System.currentTimeMillis()));
Thread.sleep(2000);
System.out.println("获取计时 = " + watch.getTime());
//暂停计时
watch.suspend();
Thread.sleep(2000);
System.out.println("获取计时 = " + watch.getTime());
//恢复暂停计时
watch.resume();
Thread.sleep(2000);
System.out.println("获取计时 = " + watch.getTime());
//停止计时,此时计时不能暂停、恢复暂停、开启,只能重置
watch.stop();
Thread.sleep(2000);
System.out.println("获取计时 = " + watch.getTime());
System.out.println("获取第一次计时开始时间="+longToString(watch.getStartTime()));
System.out.println("获取第一次计时结束时间="+longToString(watch.getStopTime()));
//重置并开始
watch.reset();
watch.start();
System.out.println("当前时间:"+longToString(System.currentTimeMillis()));
Thread.sleep(2000);
System.out.println("获取计时 = " + watch.getTime());
System.out.println("获取第二次计时开始时间="+longToString(watch.getStartTime()));
}
/**
* 时间戳转成日期
* @param time
* @return
*/
private static String longToString(long time){
LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
String s = localDateTime.format(DateTimeFormatter.ofPattern(PATTERN));
return s;
}
}