gpt4 book ai didi

java - 我如何获取日期时间戳作为 UTC

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:15:00 24 4
gpt4 key购买 nike

我将日期时间戳存储在数据库中作为 UTC 值,同时检索它时我需要将其作为 UTC 时间并需要转换为特定时区值。

即 2015-05-01 00:09:30:00 UTC 时间需要转换为 IST(或其他时区)

resultSet.getDate("VisitDate")

请帮忙解决这个问题。

最佳答案

Java 8

您可以使用设置为 UTC 的 ZonedDateTime,然后使用类似...的方式将其转换为 LocalDateTime

java.sql.Timestamp ts = resultSet.getTimestamp("VisitDate");
ZonedDateTime utcDateTime = ZonedDateTime.ofInstant(ts.toInstant(), ZoneId.of("UTC"));
LocalDateTime localDateTime = utcDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();

显然,我在示例中使用了 ZoneId.systemDefault()(将分区日期/时间转换为本地日期/时间),但您可以传递您想要/需要的任何区域

乔达时间

如果您不使用 Java 8,则与 Joda-Time 类似

java.sql.Timestamp ts = resultSet.getTimestamp("VisitDate");
LocalDateTime utcDateTime = new LocalDateTime(ts, DateTimeZone.UTC);
DateTime hereDateTime = utcDateTime.toDateTime(DateTimeZone.getDefault());

关于java - 我如何获取日期时间戳作为 UTC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30318938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com