Files
javaSE260715-new/s-day01/src/com/inmind/jdk8_date05/InstantDemo12.java
T
2026-07-30 11:59:39 +08:00

44 lines
1.5 KiB
Java

package com.inmind.jdk8_date05;
import java.time.Duration;
import java.time.Instant;
/**
* 代替Date类
* 目标:掌握Instant的使用。
*
* instant类:时间戳类------>秒,纳秒(毫秒+纳秒)
*/
public class InstantDemo12 {
public static void main(String[] args) {
//获取当前时间戳对象
Instant now = Instant.now();
System.out.println(now);//2026-07-30T02:54:10.265716800Z
//获取总秒数
long epochSecond = now.getEpochSecond();
System.out.println(epochSecond);
//获取不够1秒的纳秒数
long nano = now.getNano();
System.out.println(nano);
//加固定的纳秒值,然后返回一个新的instant对象
Instant instant1 = now.plusNanos(100);
Instant instant2 = now.minusNanos(100);
System.out.println(instant1);
System.out.println(instant2);
// Instant对象的作用:做代码的性能分析,或者记录用户的操作时间点
Instant start = Instant.now();
for (int i = 0; i < 500; i++) {
System.out.println("---------");
}
//代码的执行(50行代码的功能)
Instant end = Instant.now();
//我们会用间隔来计算时间差!!!
Duration duration = Duration.between(start, end);
System.out.println(duration.toNanos());
//传统的Date类,只能精确到毫秒,并且是可变对象,而Instant可以精确到纳秒,并且不可改变对象,推荐使用Instant,但一般LocalDateTime也够用了
}
}