[Solved] Java Date and utcTimeOffset [closed]


java.time, the modern Java date and time API

    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.

Java 8 is not an option

No big problem. java.time has been backported.

  • In Java 8 and later and on new Android devices (from API level 26, I’m told) the new API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described). Link below.
  • On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package 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.

Links

1

solved Java Date and utcTimeOffset [closed]