Convert LocalDateTime to LocalDateTime in UTC

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

    Use the below. It takes the local datetime and converts it to UTC using the timezone. You do not need to create it function.

    ZonedDateTime nowUTC = ZonedDateTime.now(ZoneOffset.UTC);
    System.out.println(nowUTC.toString());
    

    If you need to obtain the LocalDateTime part of the ZonedDateTime then you can use the following.

    nowUTC.toLocalDateTime();
    

    Here is a static method i use in my application to insert UTC time in mysql since i cannot add a default value UTC_TIMESTAMP to a datetime column.

    public static LocalDateTime getLocalDateTimeInUTC(){
        ZonedDateTime nowUTC = ZonedDateTime.now(ZoneOffset.UTC);
    
        return nowUTC.toLocalDateTime();
    }
    

提交回复
热议问题