Java 8 Convert given time and time zone to UTC time

前端 未结 3 1109
[愿得一人]
[愿得一人] 2020-12-12 22:53

I have a time with string type like: \"2015-01-05 17:00\" and ZoneId is \"Australia/Sydney\".

How can I convert this time info

3条回答
  •  离开以前
    2020-12-12 23:22

    You are looking for ZonedDateTime class in Java8 - a complete date-time with time-zone and resolved offset from UTC/Greenwich. In terms of design, this class should be viewed primarily as the combination of a LocalDateTime and a ZoneId. The ZoneOffset is a vital, but secondary, piece of information, used to ensure that the class represents an instant, especially during a daylight savings overlap.

    For example:

    ZoneId australia = ZoneId.of("Australia/Sydney");
    String str = "2015-01-05 17:00";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime localtDateAndTime = LocalDateTime.parse(str, formatter);
    ZonedDateTime dateAndTimeInSydney = ZonedDateTime.of(localtDateAndTime, australia );
    
    System.out.println("Current date and time in a particular timezone : " + dateAndTimeInSydney);
    
    ZonedDateTime utcDate = dateAndTimeInSydney.withZoneSameInstant(ZoneOffset.UTC);
    
    System.out.println("Current date and time in UTC : " + utcDate);
    

提交回复
热议问题