1.获取当前时间戳
JDK8中提供了全新的Instant类,我们可以使用这个类获取当前时间戳
long timeStamp = Instant.now().toEpochMilli();
我们也可以调用它的atZone将其转换为指定的时区时间:
Instant start = Instant.now();
ZonedDateTime time = start.atZone(ZoneId.of("Asia/Shanghai"));
然后我们想要记录时间差我们可以:
//获取当前时间线对象
Instant start = Instant.now();
Thread.sleep(2000);
Instant end = Instant.now();
//计算两个时间差
Duration duration = Duration.between(start,end);
long mills = duration.toMillis();
System.out.println("时间差为: "+mills);
完整代码以及测试结果如下:
package DateTimeApi.Exa1;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class InstantStudy {
public static void main(String[] args) throws InterruptedException {
//获取当前时间线对象
Instant start = Instant.now();
System.out.println("获取当前Instant对象 : "+start);
//将此时间线转换为中国时区时间
ZonedDateTime time = start.atZone(ZoneId.of("Asia/Shanghai"));
System.out.println("此时间线的中国时间为: "+time);
//打印当前时间戳
long timeStamp = start.toEpochMilli();
System.out.println("时间戳为:"+timeStamp);
Thread.sleep(2000);
Instant end = Instant.now();
//计算两个时间差
Duration duration = Duration.between(start,end);
long mills = duration.toMillis();
System.out.println("时间差为: "+mills);
}
}