day*_*mer 6 java datetime utc java-8 zoneddatetime
我正在使用Java 8
这就是我的ZonedDateTime样子
2013-07-10T02:52:49+12:00
Run Code Online (Sandbox Code Playgroud)
我得到这个值
z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
Run Code Online (Sandbox Code Playgroud)
这里z1是一个ZonedDateTime.
我想将此值转换为 2013-07-10T14:52:49
我怎样才能做到这一点?
小智 10
看起来您需要先转换为所需的时区 (UTC),然后才能将其发送到格式化程序。
z1.withZoneSameInstant( ZoneId.of("UTC") )
.format( DateTimeFormatter.ISO_OFFSET_DATE_TIME )
Run Code Online (Sandbox Code Playgroud)
应该给你类似的东西 2018-08-28T17:41:38.213Z
这是你想要的吗?这种转换的ZonedDateTime一个LocalDateTime给定的ZoneId由您转换ZonedDateTime到Instant之前.
LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneOffset.UTC);
Run Code Online (Sandbox Code Playgroud)
或者您可能想要用户system-timezone而不是硬编码的UTC:
LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneId.systemDefault());
Run Code Online (Sandbox Code Playgroud)
小智 5
@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) {
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15973 次 |
| 最近记录: |