Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify timezone of ZonedDateTime without changing the actual date

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.

like image 894
MatMat Avatar asked Dec 24 '22 03:12

MatMat


2 Answers

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
like image 91
Karol Dowbecki Avatar answered Dec 27 '22 11:12

Karol Dowbecki


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.

like image 22
Ole V.V. Avatar answered Dec 27 '22 12:12

Ole V.V.