ZonedDateTime to UTC with offset applied?

前端 未结 4 677
不知归路
不知归路 2020-12-31 16:31

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

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

I get this value as <

4条回答
  •  时光取名叫无心
    2020-12-31 17:08

    @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]
    

提交回复
热议问题