Convert LocalDateTime to LocalDateTime in UTC

后端 未结 10 1029
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 08:20

Convert LocalDateTime to LocalDateTime in UTC.

LocalDateTime convertToUtc(LocalDateTime date) {

    //do conversion

}

I searched over net. Bu

10条回答
  •  遥遥无期
    2021-01-30 08:30

    Try this using this method.

    convert your LocalDateTime to ZonedDateTime by using the of method and pass system default time zone or you can use ZoneId of your zone like ZoneId.of("Australia/Sydney");

    LocalDateTime convertToUtc(LocalDateTime dateTime) {
      ZonedDateTime dateTimeInMyZone = ZonedDateTime.
                                            of(dateTime, ZoneId.systemDefault());
    
      return dateTimeInMyZone
                      .withZoneSameInstant(ZoneOffset.UTC)
                      .toLocalDateTime();
      
    }
    

    To convert back to your zone local date time use:

    LocalDateTime convertFromUtc(LocalDateTime utcDateTime){
        return ZonedDateTime.
                of(utcDateTime, ZoneId.of("UTC"))
                .toOffsetDateTime()
                .atZoneSameInstant(ZoneId.systemDefault())
                .toLocalDateTime();
    }
    

提交回复
热议问题