1. System.currentTimeMillis()获取时间毫秒数,从1971-01-01开始算
package com.xin.demo.timedemo;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeUtilDemo1 {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
System.out.println(formatter.format(date));
long totalMilisSeconds = System.currentTimeMillis();
long totalSeconds = totalMilisSeconds / 1000;
long currentSeconds = totalSeconds % 60;
long totalMinutes = totalSeconds / 60;
System.out.println("总毫秒数:"+totalMilisSeconds);
System.out.println("总秒数:"+totalSeconds);
System.out.println("总分钟数:"+totalMinutes);
long time1 = System.currentTimeMillis();
try {
Thread.sleep(4);
} catch (Throwable E) {
}
long time2 = System.currentTimeMillis();
long period = time2 -time1;
System.out.println("period milli: " + period);
System.out.println("period second: " + period/1000);
}
}
2. 使用StopWatch用来计时
import org.apache.commons.lang3.time.StopWatch;
public class StopWatchDemo {
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Thread.sleep(1000);
stopWatch.split();
System.out.println("子任务1耗时:" + stopWatch.getTime() + " 毫秒");
Thread.sleep(2000);
stopWatch.split();
System.out.println("子任务2耗时:" + (stopWatch.getTime() - stopWatch.getSplitTime()) + " 毫秒");
stopWatch.unsplit();
Thread.sleep(1500);
stopWatch.stop();
System.out.println("总耗时:" + stopWatch.getTime() + " 毫秒");
}
}