将OffsetDateTime转换为UTC时间戳

将OffsetDateTime转换为UTC时间戳

本文介绍了将OffsetDateTime转换为UTC时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 java.time.OffsetDateTime 我想将其转换为 java.sql.Timestamp 。由于 Timestamp 不存储任何偏移信息,我将以UTC格式存储数据库中的所有日期/时间。

I have an java.time.OffsetDateTime which I would like to convert to a java.sql.Timestamp. Since Timestamp doesn't store any offset information, I am going to store all dates/times in the database as UTC.

如何将 OffsetDateTime 转换为UTC中的时间戳

How do I convert the OffsetDateTime to a Timestamp which is in UTC?

编辑:

我相信这是答案,但似乎是一种相当复杂的方式来转换为UTC:

I believe this is the answer but it seems are rather convoluted way to covert to UTC:

OffsetDateTime dateTime = OffsetDateTime.now();
Timestamp timestamp = Timestamp.valueOf(dateTime.atZoneSameInstant(ZoneId.of("Z")).toLocalDateTime());


推荐答案

这将是一种转换方式并确保使用UTC。我认为比使用纪元秒提出的解决方案更清晰。

This would be a way to do the conversion and ensure UTC is used. That I think is a little cleaner than solution proposed using the epoch seconds.

Timestamp test = Timestamp.valueOf(entityValue.atZoneSameInstant(ZoneOffset.UTC).toLocalDateTime());

这篇关于将OffsetDateTime转换为UTC时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 23:19