Convert LocalDateTime to LocalDateTime in UTC

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

    Here's a simple little utility class that you can use to convert local date times from zone to zone, including a utility method directly to convert a local date time from the current zone to UTC (with main method so you can run it and see the results of a simple test):

    import java.time.LocalDateTime;
    import java.time.ZoneId;
    import java.time.ZoneOffset;
    import java.time.ZonedDateTime;
    
    public final class DateTimeUtil {
        private DateTimeUtil() {
            super();
        }
    
        public static void main(final String... args) {
            final LocalDateTime now = LocalDateTime.now();
            final LocalDateTime utc = DateTimeUtil.toUtc(now);
    
            System.out.println("Now: " + now);
            System.out.println("UTC: " + utc);
        }
    
        public static LocalDateTime toZone(final LocalDateTime time, final ZoneId fromZone, final ZoneId toZone) {
            final ZonedDateTime zonedtime = time.atZone(fromZone);
            final ZonedDateTime converted = zonedtime.withZoneSameInstant(toZone);
            return converted.toLocalDateTime();
        }
    
        public static LocalDateTime toZone(final LocalDateTime time, final ZoneId toZone) {
            return DateTimeUtil.toZone(time, ZoneId.systemDefault(), toZone);
        }
    
        public static LocalDateTime toUtc(final LocalDateTime time, final ZoneId fromZone) {
            return DateTimeUtil.toZone(time, fromZone, ZoneOffset.UTC);
        }
    
        public static LocalDateTime toUtc(final LocalDateTime time) {
            return DateTimeUtil.toUtc(time, ZoneId.systemDefault());
        }
    }
    

提交回复
热议问题