首页  

java 各种日期时间转换     所属分类 java 浏览量 50
java.time.Instant  是 Java 时间 API 中的一个核心类,用于表示时间轴上的一个瞬时点,具有高精度和无时区依赖的特点。
它在处理时间戳、时间计算以及与其他日期时间类的互转中发挥着重要作用。

通过 java.time.Instant ,实现各种日期时间的互相转换



import java.time.*;
import java.util.Date;


        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);

        final Date dateNow =  new Date(instantNow.toEpochMilli());

        System.out.println(instantNow);
        System.out.println(dateNow);
        System.out.println(localDateTimeNow);
        System.out.println(offsetDateTimeNow);
        System.out.println(zonedDateTimeNow);

        System.out.println(instantNow.toEpochMilli());
        System.out.println(dateNow.getTime());
        System.out.println(localDateTimeNow.toInstant(zoneOffset).toEpochMilli());
        System.out.println(offsetDateTimeNow.toInstant().toEpochMilli());
        System.out.println(zonedDateTimeNow.toInstant().toEpochMilli());

        System.out.println(dateNow.toInstant());


        // 获取当前时间戳
        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);


Asia/Shanghai Z +08:00 2024-08-25T00:32:26.072Z Sun Aug 25 08:32:26 CST 2024 2024-08-25T08:32:26.072 2024-08-25T08:32:26.072+08:00 2024-08-25T08:32:26.072+08:00[Asia/Shanghai] 1724545946072 1724545946072 1724545946072 1724545946072 1724545946072 2024-08-25T00:32:26.072Z 当前时间: 2024-08-25T00:32:26.098Z Instant 字符串表示: 2024-08-25T00:32:26.098Z 两个时间点之间的持续时间: PT-564H-32M-26.098S

上一篇     下一篇
Java各种数据对象转换框架

java8的日期时间

java.time.Instant 说明

jdbc spi 实例

nodejs hello

mybatis 获取自动生成的键值