QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 2781|回复: 0

[JAVA/JSP] Java8中ZonedDateTime与Timestamp的相互转换

[复制链接]

等级头衔

积分成就    金币 : 2861
   泡泡 : 1516
   精华 : 6
   在线时间 : 1322 小时
   最后登录 : 2026-1-12

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老活跃会员

联系方式
发表于 2020-12-5 11:33:12 | 显示全部楼层 |阅读模式
       Jdk8中java.time包中的新的日期时间API类中时间范围示意图:可以很清晰的看出ZonedDateTime相当于LocalDateTime+ZoneId,ZonedDateTime是用来处理时区相关的时间。
+ U# z, s$ P$ h: h 1.jpg ' t/ ^" H* `! L  r1 j( l
1. ZonedDateTime->时间戳  M* o5 j. G- i! Q$ M+ T; h
package com.mkyong.jdbc;

import java.sql.Timestamp;
import java.time.ZonedDateTime;

public class TimeExample1 {

    public static void main(String[] args) {

        ZonedDateTime now = ZonedDateTime.now();

        // 1. ZonedDateTime to TimeStamp
        Timestamp timestamp = Timestamp.valueOf(now.toLocalDateTime());

        // 2. ZonedDateTime to TimeStamp , no different
        Timestamp timestamp2 = Timestamp.from(now.toInstant());

        System.out.println(now); // 2019-06-19T14:12:13.585294800+08:00[Asia/Kuala_Lumpur]

        System.out.println(timestamp); // 2019-06-19 14:12:13.5852948

        System.out.println(timestamp2); // 2019-06-19 14:12:13.5852948

    }
}
输出量:
1 g8 x9 E# `) t, i( w9 s+ w. z 2.jpg 6 ?  x; S, G  N. {' n- L
2.时间戳-> ZonedDateTime
! E. V4 z- g) s4 \5 A/ T, B" @: z
package com.mkyong;

import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class TimeExample2 {

    public static void main(String[] args) {

        Timestamp timestamp = Timestamp.from(Instant.now());

        LocalDateTime localDateTimeNoTimeZone = timestamp.toLocalDateTime();

        ZonedDateTime zonedDateTime1 = localDateTimeNoTimeZone.atZone(ZoneId.of("+08:00"));

        ZonedDateTime zonedDateTime2 = localDateTimeNoTimeZone.atZone(ZoneId.of("Asia/Kuala_Lumpur"));

        ZonedDateTime zonedDateTime3 = localDateTimeNoTimeZone.atZone(ZoneId.systemDefault());

        ZonedDateTime zonedDateTime4 = localDateTimeNoTimeZone.atZone(ZoneId.of("-08:00"));

        System.out.println(timestamp); // 2019-06-19 14:08:23.4458984

        System.out.println(zonedDateTime1); // 2019-06-19T14:08:23.445898400+08:00

        System.out.println(zonedDateTime2); // 2019-06-19T14:08:23.445898400+08:00[Asia/Kuala_Lumpur]

        System.out.println(zonedDateTime3); // 2019-06-19T14:08:23.445898400+08:00[Asia/Kuala_Lumpur]

        System.out.println(zonedDateTime4); // 2019-06-19T14:08:23.445898400-08:00

    }

}
输出量:6 [$ `9 C) \8 @6 ^& l' s# P- K
3.jpg ) J3 a" ]# A1 \) U! v, c4 x- i9 d
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2026-2-3 00:34

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表