ZonedDateTime到UTC并应用了偏移量?

问题描述 投票:6回答:3

我正在使用Java 8 这就是我的ZonedDateTime的样子

2013-07-10T02:52:49+12:00

我得到这个值

z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)

其中z1ZonedDateTime

我想将此值转换为2013-07-10T14:52:49

我怎样才能做到这一点?

java datetime java-8 utc zoneddatetime
3个回答
8
投票

这是你想要的吗?通过将你的ZonedDateTime转换为LocalDateTime,你可以将你的ZoneId转换为带有ZonedDateTimeInstant

LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneOffset.UTC);

或者您可能想要用户system-timezone而不是硬编码的UTC:

LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneId.systemDefault());

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]

1
投票

看起来您需要在将其发送到格式化程序之前转换为所需的时区(UTC)。

z1.withZoneSameInstant( ZoneId.of("UTC") )
  .format( DateTimeFormatter.ISO_OFFSET_DATE_TIME )

应该给你像2018-08-28T17:41:38.213Z的东西

© www.soinside.com 2019 - 2024. All rights reserved.