I have a Date object which holds a date (not current date) and I need to somehow specify that this date is UTC and then convert it to "Europe/Paris" which is +1 hours.
public static LocalDateTime toLocalDateTime(Date date){
return ZonedDateTime.of(LocalDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC), ZoneId.of("Europe/Paris")).toLocalDateTime();
}
Given a date of "2018-11-08 15:00:00" this converts the date into "2018-11-08 14:00:00". I need it to convert from UTC to Europe/Paris - not the other way around.
You could use ZonedDateTime.withZoneSameInstant() method to move from UTC to Paris time:
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());
which prints:
2018-11-08T10:25:18.223Z
2018-11-08T11:25:18.223+01:00[Europe/Paris]
2018-11-08T11:25:18.223
Since an old-fashioned Date object doesn’t have any time zone, you can ignore UTC completely and just convert to Europe/Paris directly:
private static final ZoneId TARGET_ZONE = ZoneId.of("Europe/Paris");
public static LocalDateTime toLocalDateTime(Date date){
return date.toInstant().atZone(TARGET_ZONE).toLocalDateTime();
}
I’m not sure why you want to return a LocalDateTime, though. That is throwing away information. For most purposes I’d leave out .toLocalDateTime() and just return the ZonedDateTime from atZone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With