我需要将LocalDateTime转换为UTC日期,这是我的代码
LocalDateTime ldt = LocalDateTime.now();
System.out.println("Local date Time " +ldt);
ZonedDateTime ldtZoned = ldt.atZone(ZoneId.systemDefault());
ZonedDateTime utcZoned = ldtZoned.withZoneSameInstant(ZoneOffset.UTC);
System.out.println("UTC Zone"+utcZoned);
Instant i = utcZoned.toInstant();
System.out.println("Instant "+i);
Date out = Date.from(i);
System.out.println("date from Instant "+ out);
输出为
Local date Time 2019-05-08T16:23:53.109
UTC Zone2019-05-08T22:23:53.109Z
Instant 2019-05-08T22:23:53.109Z
date from Instant Wed May 08 16:23:53 MDT 2019
直到第3条陈述都很好。但是,当我们从Instant获取Date对象时,它将Date对象转换回本地时间。
我们如何从LocaldateTime获取Date对象作为UTC?