Convert LocalDateTime to LocalDateTime in UTC

后端 未结 10 1046
爱一瞬间的悲伤
爱一瞬间的悲伤 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:35

    LocalDateTime does not contain Zone information. ZonedDatetime does.

    If you want to convert LocalDateTime to UTC, you need to wrap by ZonedDateTime fist.

    You can convert like the below.

    LocalDateTime ldt = LocalDateTime.now();
    System.out.println(ldt.toLocalTime());
    
    ZonedDateTime ldtZoned = ldt.atZone(ZoneId.systemDefault());
    
    ZonedDateTime utcZoned = ldtZoned.withZoneSameInstant(ZoneId.of("UTC"));
    
    System.out.println(utcZoned.toLocalTime());
    

提交回复
热议问题