java.time.Instant 说明  
   
所属分类 java
浏览量 534
java.time.Instant  是 Java 8 引入的一个类,用于表示时间轴上的一个瞬时点。
它通常以纳秒精度表示,并且不持有任何时区信息。
这个类扩展了 Object 类并实现了 Temporal, TemporalAdjuster, Comparable< Instant> 和 Serializable 接口。
java.time.Instant  是 Java 时间 API 中的一个核心类,用于表示时间轴上的一个瞬时点,具有高精度和无时区依赖的特点。
它在处理时间戳、时间计算以及与其他日期时间类的互转中发挥着重要作用。
主要用途和特点
时间戳:Instant 类可以用来生成表示机器时间的时间戳,这些时间戳从 1970 年 1 月 1 日(1970-01-01T00:00:00Z)的第一秒开始计算。
时间计算:它主要用于时间计算和系统时钟,可以记录事件发生的时间或测量两个瞬间之间的持续时间。
与其它日期时间类的关系:
LocalDateTime 表示没有时区的日期和时间,而 Instant 表示时间线上的一个瞬时点。
可以将 Instant 对象加上时区后转换为 LocalDateTime,但后者只可以理解为 Instant 在某个时区中的表现。
import java.time.Instant ;
public class InstantExample {
    public static void main(String[] args) {
        // 获取当前时间戳
        Instant now = Instant.now ();
        System.out.println ("当前时间: " + now);
        // 将 Instant 转换为字符串
        String instantString = now.toString ();
        System.out.println ("Instant 字符串表示: " + instantString);
        // 计算两个 Instant 之间的差值
        Instant anotherTime = Instant.parse ("2024-08-01T12:00:00Z");
        Duration duration = Duration.between (now, anotherTime);
        System.out.println ("两个时间点之间的持续时间: " + duration);
    }
}
当前时间: 2024-08-25T00:23:34.475Z
Instant 字符串表示: 2024-08-25T00:23:34.475Z
两个时间点之间的持续时间: PT-564H-23M-34.475S
        final ZoneId zoneId = ZoneId.systemDefault();
        System.out.println(zoneId);
        System.out.println(ZoneOffset.UTC);
        final Instant instantNow = Instant.now();
        final ZoneOffset zoneOffset = ZoneId.systemDefault().getRules().getOffset(instantNow);
        System.out.println(zoneOffset);
        final LocalDateTime localDateTimeNow =  LocalDateTime.ofInstant(instantNow,zoneId) ;
        OffsetDateTime offsetDateTimeNow = OffsetDateTime.ofInstant(instantNow,zoneId);
        ZonedDateTime zonedDateTimeNow = ZonedDateTime.ofInstant(instantNow,zoneId);
        System.out.println(instantNow);
        System.out.println(localDateTimeNow);
        System.out.println(offsetDateTimeNow);
        System.out.println(zonedDateTimeNow);
        System.out.println(instantNow.toEpochMilli());
        System.out.println(localDateTimeNow.toInstant(zoneOffset).toEpochMilli());
        System.out.println(offsetDateTimeNow.toInstant().toEpochMilli());
        System.out.println(zonedDateTimeNow.toInstant().toEpochMilli());
Asia/Shanghai
Z
+08:00
2024-08-25T00:10:20.548Z
2024-08-25T08:10:20.548
2024-08-25T08:10:20.548+08:00
2024-08-25T08:10:20.548+08:00[Asia/Shanghai]
1724544620548
1724544620548
1724544620548
1724544620548
 上一篇  
   
 下一篇  
 springboot jpa 实例 
 Java各种数据对象转换框架 
 java8的日期时间 
 java 各种日期时间转换 
 jdbc spi 实例 
 nodejs hello