我正在使用Java 8
这就是我的ZonedDateTime
看起来像
2013-07-10T02:52:49+12:00
我将此值视为
z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
其中z1
是ZonedDateTime
。
我想将此值转换为2013-07-10T14:52:49
我该怎么做?
答案 0 :(得分:8)
ZonedDateTime
转换为LocalDateTime
之前,这会将您的ZoneId
转换为ZonedDateTime
Instant
。
LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneOffset.UTC);
或许你想要用户系统时区而不是硬编码的UTC:
LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneId.systemDefault());
答案 1 :(得分:3)
@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]
答案 2 :(得分:1)
您似乎需要先转换为所需的时区(UTC),然后再将其发送给格式化程序。
z1.withZoneSameInstant( ZoneId.of("UTC") )
.format( DateTimeFormatter.ISO_OFFSET_DATE_TIME )
应该给您类似2018-08-28T17:41:38.213Z
答案 3 :(得分:0)
如果z1
是ZonedDateTime
的实例,则表达式
z1.withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime()
使用OP请求的字符串表示形式求值为LocalDateTime
的实例。下面的程序对此进行了说明:
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
ZonedDateTime time = ZonedDateTime.now();
ZonedDateTime truncatedTime = time.truncatedTo(ChronoUnit.SECONDS);
ZonedDateTime truncatedTimeUtc = trucatedTime.withZoneSameInstant(ZoneOffset.UTC);
LocalDateTime truncatedTimeUtcNoZone = truncatedTimeUtc.toLocalDateTime();
System.out.println(time);
System.out.println(trucatedTime);
System.out.println(truncatedTimeUtc);
System.out.println(truncatedTimeUtcNoZone);
}
}
以下是示例输出:
2020-10-26T16:45:21.735836-03:00[America/Sao_Paulo]
2020-10-26T16:45:21-03:00[America/Sao_Paulo]
2020-10-26T19:45:21Z
2020-10-26T19:45:21