I have a Java Date (java.util.Date
) - Tue Jul 31 00:53:43 CEST 2018 and a utcTimeOffset = +0200, which says that give, date is +2 hours from UTC.
This is a legacy code and Java 8 is not an option. What I am getting is text representation of date as 20180730131847
and utcTimeOffset = +0200
from a third-party API.
I would like to convert this to Danish time. Can someone help me how to do this please.
ZoneId danishTime = ZoneId.of("Europe/Copenhagen");
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmss");
DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("XX");
String dateTimeString = "20180730131847";
String offsetString = "+0200";
ZoneOffset offset = ZoneOffset.from(offsetFormatter.parse(offsetString));
ZonedDateTime dateTime = LocalDateTime.parse(dateTimeString, dateTimeFormatter)
.atOffset(offset)
.atZoneSameInstant(danishTime);
System.out.println("Danish time: " + dateTime);
Output from this code is:
Danish time: 2018-07-30T13:18:47+02:00[Europe/Copenhagen]
The time zone to use for Denmark is Europe/Copenhagen. While the Faroe islands and Greenland use other time zones and are in a national community (“rigsfællesskab”) with Denmark under the same queen, they are not part of Denmark proper, so can be ignored when Danish time is asked for. Since Danish summer time agrees with your example offset of +0200, in this case we get the same time out as we put in. With a date in winter, for example, this would not have been the case because Danish standard time is at offset +0100.
No big problem. java.time has been backported.
org.threeten.bp
and subpackages.In the backport the classes are in package org.threeten.bp
with subpackages, for example org.threeten.bp.ZoneId
and org.threeten.bp.format.DateTimeFormatter
.
java.time
.