我使用Java 8
这是我ZonedDateTime
看起来像ZonedDateTime到UTC并应用偏移量?
2013-07-10T02:52:49+12:00
我得到这个值作为
z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
其中z1
是ZonedDateTime
。
我想这个值作为2013-07-10T14:52:49
我怎么能这样做转换?
我使用Java 8
这是我ZonedDateTime
看起来像ZonedDateTime到UTC并应用偏移量?
2013-07-10T02:52:49+12:00
我得到这个值作为
z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
其中z1
是ZonedDateTime
。
我想这个值作为2013-07-10T14:52:49
我怎么能这样做转换?
这是你想要的吗? 这会将您的ZonedDateTime
转换为LocalDateTime
,给定的ZoneId
将ZonedDateTime
转换为Instant
。
LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneId.of("UTC"));
或者,也许你希望用户系统时区,而不是硬编码UTC:
LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneId.systemDefault());
@SimMac感谢您的清晰度。我也面临同样的问题,并能根据他的建议找到答案。
public static void main(String[] args) {
try {
String dateTime = "MM/dd/yyyy HH:mm:ss";
String date = "09/17/2017 20:53:31";
Integer gmtPSTOffset = -8;
ZoneOffset offset = ZoneOffset.ofHours(gmtPSTOffset);
// String to LocalDateTime
LocalDateTime ldt = LocalDateTime.parse(date, DateTimeFormatter.ofPattern(dateTime));
// Set the generated LocalDateTime's TimeZone. In this case I set it to UTC
ZonedDateTime ldtUTC = ldt.atZone(ZoneOffset.UTC);
System.out.println("UTC time with Timezone : "+ldtUTC);
// Convert above UTC to PST. You can pass ZoneOffset or Zone for 2nd parameter
LocalDateTime ldtPST = LocalDateTime.ofInstant(ldtUTC.toInstant(), offset);
System.out.println("PST time without offset : "+ldtPST);
// If you want UTC time with timezone
ZoneId zoneId = ZoneId.of("America/Los_Angeles");
ZonedDateTime zdtPST = ldtUTC.toLocalDateTime().atZone(zoneId);
System.out.println("PST time with Offset and TimeZone : "+zdtPST);
} catch (Exception e) {
}
}
输出:
UTC time with Timezone : 2017-09-17T20:53:31Z
PST time without offset : 2017-09-17T12:53:31
PST time with Offset and TimeZone : 2017-09-17T20:53:31-08:00[America/Los_Angeles]
我还是不明白:d。它与http://stackoverflow.com/q/35688559/1743880有何不同? “convert to'2013-07-10T14:52:49'”是什么意思? – Tunaki
将'+12小时'应用于'02:52:49'以使它成为'14:52:59',现在清楚了吗? – daydreamer
所以你想在未来的12小时内为同一区域偏移? – Tunaki