我正在使用Java 8
这就是我的ZonedDateTime
的样子
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(), ZoneOffset.UTC);
或者您可能想要用户system-timezone而不是硬编码的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]
看起来您需要在将其发送到格式化程序之前转换为所需的时区(UTC)。
z1.withZoneSameInstant( ZoneId.of("UTC") )
.format( DateTimeFormatter.ISO_OFFSET_DATE_TIME )
应该给你像2018-08-28T17:41:38.213Z
的东西