如何使用Java 8库将UTC日期时间转换为另一个时区? [英] How to convert UTC DateTime to another Time Zone using Java 8 library?
问题描述
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
.>
然后将 But I want to get the converted date time as 2031-04-26 00:00:00+5:30 as my timestamp value is in the UTC Timezone. Please help. First, you should not use You then zone that
这篇关于如何使用Java 8库将UTC日期时间转换为另一个时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!LocalDateTime
分区为UTC,然后使用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]
Timestamp
. You can use DateTimeFormatter
to parse into a LocalDateTime
.LocalDateTime
to UTC before converting to the Calcutta zone with ZonedDateTime.withZoneSameInstant
.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);