如何根据 LocalDateTime 中的时区更改时间,这里我已经建立了一个时区为 EST 的日期,现在我需要找到 UTC 的相应时间。请帮我解决这个问题
String str = "16Jun2015_153556";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyyyy_HHmmss");
formatter.withZone(ZoneId.of("EST5EDT"));
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
最佳答案
您不应该考虑“更改时区”的 LocalDateTime
- LocalDateTime
没有 时区。相反,您应该从 LocalDateTime
和时区 (ZoneId
) 构建一个 ZonedDateTime
。首先删除 formatter.withZone
调用,然后使用:
ZonedId zone = ZoneId.of("EST5EDT"); // Or preferrably "America/New_York"
ZonedDateTime zoned = ZonedDateTime.of(dateTime, zone);
然后您可以将其转换为瞬间,或者使用:
ZonedDateTime utc = zoned.withZoneSameInstant(ZoneOffset.UTC);
例如:
import java.time.*;
import java.time.format.*;
public class Test {
public static void main(String[] args) {
String str = "16Jun2015_153556";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyyyy_HHmmss");
ZoneId zone = ZoneId.of("America/New_York");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
ZonedDateTime zoned = ZonedDateTime.of(dateTime, zone);
// Both of these print 2015-06-16T19:35:56Z
System.out.println(zoned.toInstant());
System.out.println(zoned.withZoneSameInstant(ZoneOffset.UTC));
}
}
关于java - 使用 java.time 根据时区转换时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30872473/