Convert LocalDateTime to LocalDateTime in UTC

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

    tldr: there is simply no way to do that; if you are trying to do that, you get LocalDateTime wrong.

    The reason is that LocalDateTime does not record Time Zone after instances are created. You cannot convert a date time without time zone to another date time based on a specific time zone.

    As a matter of fact, LocalDateTime.now() should never be called in production code unless your purpose is getting random results. When you construct a LocalDateTime instance like that, this instance contains date time ONLY based on current server's time zone, which means this piece of code will generate different result if it is running a server with a different time zone config.

    LocalDateTime can simplify date calculating. If you want a real universally usable data time, use ZonedDateTime or OffsetDateTime: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html.

提交回复
热议问题