gpt4 book ai didi

java - 如何使用 Java 8 库将 UTC DateTime 转换为另一个时区?

转载 作者:行者123 更新时间:2023-12-05 08:20:16 24 4
gpt4 key购买 nike

final Timestamp rawDateTime = Timestamp.valueOf("2031-04-25 18:30:00");
final ZoneId zoneId = ZoneId.of("Asia/Calcutta");
final ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(
Instant.ofEpochMilli(rawDateTime.getTime()), zoneId);
// here we are getting output as 2031-04-25T18:30+05:30[Asia/Calcutta]

final ZonedDateTime zonedDateTime1 =
ZonedDateTime.of(rawDateTime.toLocalDateTime(), zoneId);
// here we are getting output as 2031-04-25T18:30+05:30[Asia/Calcutta]

但我想将转换后的日期时间设为 2031-04-26 00:00:00+5:30,因为我的时间戳值在 UTC 时区中。

请帮忙。

最佳答案

首先,你不应该使用Timestamp。您可以使用 DateTimeFormatter解析为 LocalDateTime .

然后,在使用 ZonedDateTime.withZoneSameInstant 转换为加尔各答时区之前,将 LocalDateTime 区划为 UTC .

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.toFormatter();

LocalDateTime localDateTime = LocalDateTime.parse("2031-04-25 18:30:00", formatter);
ZoneId calcuttaZone = ZoneId.of("Asia/Calcutta");
ZonedDateTime calcuttaZonedDateTime = localDateTime.atZone(ZoneOffset.UTC)
.withZoneSameInstant(calcuttaZone);

关于java - 如何使用 Java 8 库将 UTC DateTime 转换为另一个时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54108388/

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