时间与日期——瞬时(Instant)

2022年12月5日09:57:30

JAVA中的时间与日期——瞬时(Instant)

瞬时(Instant):

Instant:时间线上的一个瞬时点。 这可能被用来记录应用程序中的事件时间戳。

在处理时间和日期的时候,我们通常会想到年,月,日,时,分,秒。然而,这只是时间的一个模型,是面向人类的。第二种通用模型是面向机器的,或者说是连续的。在此模型中,时间线中的一个点表示为一个很大的数,这有利于计算机处理。在UNIX中,这个数从1970年开始,以秒为的单位;同样的,在Java中,也是从1970年开始,但以毫秒为单位。

java.time包通过值类型Instant提供机器视图,不提供处理人类意义上的时间单位。Instant表示时间线上的一点,而不需要任何上下文信息,例如,时区。概念上讲,它只是简单的表示自1970年1月1日0时0分0秒(UTC)开始的秒数。因为java.time包是基于纳秒计算的,所以Instant的精度可以达到纳秒级。

(1 ns = 10-9 s) 1秒 = 1000毫秒 =106微秒=109纳秒

常用方法介绍

now() 静态方法,返回默认UTC时区的Instant类的对象
ofEpochMilli(long epochMilli) 静态方法,返回在1970-01-01 00:00:00基础上加上指定毫秒数之后的Instant类的对象
atOffset(ZoneOffset offset) 结合即时的偏移来创建一个 OffsetDateTime
toEpochMilli() 返回1970-01-01 00:00:00到当前时间的毫秒数,即为时间戳

时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。

代码分步解析

publicclassInstantTest{@Testpublicvoidtest1(){
        Instant instant= Instant.now();//获取本初子午线时间
        System.out.println(instant+"\n");

运行结果:
时间与日期——瞬时(Instant)
如果想获取北京时间怎么办呢?则需用另一个方法atOffset(ZoneOffset offset)添加一个时间偏移量

//结合即时的偏移来创建一个 OffsetDateTime;添加时间偏移量
        OffsetDateTime offsetDateTime= instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime+"\n");

运行结果:
时间与日期——瞬时(Instant)
为啥偏移量是8小时呢,请看下图,因为北京所处的时区在东八区,所以加了8小时。
时间与日期——瞬时(Instant)
前面有提到,在处理时间和日期的时候,在Java中,是从1970年开始,以毫秒为单位。如何获取1970-01-01 00:00:00到当前时间的毫秒数?请用toEpochMilli()方法。

//获取1970-01-01 00:00:00到当前时间的毫秒数,即为时间戳long milli= instant.toEpochMilli();
        System.out.println(milli+"\n");

运行结果:
时间与日期——瞬时(Instant)
最后一个常用方法:ofEpochMilli(long epochMilli) 静态方法,返回在1970-01-01 00:00:00基础上加上指定毫秒数之后的Instant类的对象

//给定特定的毫秒数,获取Instant实例
        Instant instant1= Instant.ofEpochMilli((1617760900204L));
        System.out.println(instant1);
        OffsetDateTime offsetDateTime1= instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime1+"\n");

运行结果:
时间与日期——瞬时(Instant)
也要通过加时间偏移量来获取北京时间。

完整代码:

publicclassInstantTest{@Testpublicvoidtest1(){
        Instant instant= Instant.now();//获取本初子午线时间
        System.out.println(instant+"\n");//结合即时的偏移来创建一个 OffsetDateTime;添加时间偏移量
        OffsetDateTime offsetDateTime= instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime+"\n");//获取1970-01-01 00:00:00到当前时间的毫秒数,即为时间戳long milli= instant.toEpochMilli();
        System.out.println(milli+"\n");//给定特定的毫秒数,获取Instant实例
        Instant instant1= Instant.ofEpochMilli((1617760900204L));
        System.out.println(instant1);
        OffsetDateTime offsetDateTime1= instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime1+"\n");//给定特定的秒数,获取Instant实例
        Instant instant2= Instant.ofEpochSecond(instant.getEpochSecond());
        System.out.println(instant2+"\n");}}

运行结果图:
时间与日期——瞬时(Instant)

  • 作者:秃头黑旋风
  • 原文链接:https://blog.csdn.net/Passerby_Tang/article/details/115470120
    更新时间:2022年12月5日09:57:30 ,共 2333 字。