MatMat
MatMat

Reputation: 908

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.

Upvotes: 8

Views: 19422

Answers (3)

Anonymous
Anonymous

Reputation: 86296

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.

Upvotes: 1

Karol Dowbecki
Karol Dowbecki

Reputation: 44962

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

Upvotes: 15

malvern dongeni
malvern dongeni

Reputation: 681

 ZonedId zoneId = ZoneId.of("Europe/Paris");
 return ZonedDateTime.of(LocalDateTime.ofInstant(date.toInstant(),zonedId);

Try to define ZoneId that is Europe/Paris

Upvotes: 0

Related Questions