Java 指定ZoneDateTime的时区,而不更改实际日期
我有一个Date对象,它保存一个日期(不是当前日期),我需要以某种方式指定该日期为UTC,然后将其转换为“Europe/Paris”,即+1小时Java 指定ZoneDateTime的时区,而不更改实际日期,java,date,timezone,zoneddatetime,Java,Date,Timezone,Zoneddatetime,我有一个Date对象,它保存一个日期(不是当前日期),我需要以某种方式指定该日期为UTC,然后将其转换为“Europe/Paris”,即+1小时 public static LocalDateTime toLocalDateTime(Date date){ return ZonedDateTime.of(LocalDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC), ZoneId.of("Europe/Paris")).toLocal
public static LocalDateTime toLocalDateTime(Date date){
return ZonedDateTime.of(LocalDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC), ZoneId.of("Europe/Paris")).toLocalDateTime();
}
如果日期为“2018-11-08 15:00:00”,则将日期转换为“2018-11-08 14:00:00”。我需要它从UTC转换到欧洲/巴黎-而不是相反
ZonedId zoneId = ZoneId.of("Europe/Paris");
return ZonedDateTime.of(LocalDateTime.ofInstant(date.toInstant(),zonedId);
尝试定义区域ID,即欧洲/巴黎您可以使用方法从UTC移动到巴黎时间:
Date date = new Date();
ZonedDateTime utc = date.toInstant().atZone(ZoneOffset.UTC);
ZonedDateTime paris = utc.withZoneSameInstant(ZoneId.of("Europe/Paris"));
System.out.println(utc);
System.out.println(paris);
System.out.println(paris.toLocalDateTime());
其中打印:
2018-11-08T10:25:18.223Z
2018-11-08T11:25:18.223+01:00[Europe/Paris]
2018-11-08T11:25:18.223
由于老式的
日期
对象没有任何时区,您可以完全忽略UTC,直接转换到欧洲/巴黎:
private static final ZoneId TARGET_ZONE = ZoneId.of("Europe/Paris");
public static LocalDateTime toLocalDateTime(Date date){
return date.toInstant().atZone(TARGET_ZONE).toLocalDateTime();
}
但是,我不确定为什么要返回
LocalDateTime
。这是在浪费信息。在大多数情况下,我会省去.toLocalDateTime()
,直接从atZone
返回ZoneDateTime
,这应该会有帮助:当您可以直接从Instant
构建ZoneDateTime
时,为什么要通过LocalDateTime
?