如何制作java.sql.Timestamp UTC时间? [英] How do I make java.sql.Timestamp UTC time?

查看:120
本文介绍了如何制作java.sql.Timestamp UTC时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static void main(String[] args) {

    LocalDateTime ldt = LocalDateTime.now();

    ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());

    Instant instant = Instant.from(zdt);

    Timestamp timestamp = Timestamp.from(instant);

    System.out.println(ldt + "\n");

    System.out.println(zdt + "\n");

    System.out.println(instant + "\n");

    System.out.println(timestamp + "\n");
}

并打印出来:

2017-05-07T18:13:26.969

2017-05-07T18:13:26.969-04:00[America/New_York]

2017-05-07T22:13:26.969Z

2017-05-07 18:13:26.969

如何在 Instant 时间戳保存$ C>?我需要能够从任何地方获得时间戳并将其转换为它在世界的任何时间。问题在于它与我的系统时钟恰好设置在同一时间保存。

How can I make an SQL Timestamp save with the same time as the Instant? I need to be able to get the Timestamp from anywhere and convert it to whatever time it happens to be in that part of the world. The problem is that it keeps saving as the same time as whatever my system clock happens to be set at.

推荐答案

你是最好的从 LocalDateTime 获取时间戳,而不是从 Instant

You are best to get a Timestamp from a LocalDateTime, rather than from an Instant.

第一步是拿走 ZonedDateTime 并将其转换为GMT:

The first step is to take your ZonedDateTime and convert it to GMT:

ZonedDateTime gmt = zdt.withZoneSameInstant(ZoneId.of("GMT"));

然后你可以将它转换为时间戳通过 LocalDateTime

Then you can convert it to a Timestamp via a LocalDateTime:

Timestamp timestamp = Timestamp.valueOf(gmt.toLocalDateTime());

这篇关于如何制作java.sql.Timestamp UTC时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆