ZonedDateTime to UTC with offset applied?

若如初见. 提交于 2020-01-01 10:07:56

问题


I am using Java 8
This is what my ZonedDateTime looks like

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

I get this value as

z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)

where z1 is a ZonedDateTime.

I wanted to convert this value as 2013-07-10T14:52:49

How can I do that?


回答1:


Is this what you want? This converts your ZonedDateTime to a LocalDateTime with a given ZoneId by converting your ZonedDateTime to an Instant before.

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

Or maybe you want the users system-timezone instead of hardcoded UTC:

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



回答2:


@SimMac Thanks for the clarity. I also faced the same issue and able to find the answer based on his suggestion.

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) {
    }
}

Output:

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]



回答3:


It looks like you need to convert to the desired time zone (UTC) before sending it to the formatter.

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

should give you something like 2018-08-28T17:41:38.213Z



来源:https://stackoverflow.com/questions/35689123/zoneddatetime-to-utc-with-offset-applied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!