Search code examples
javatimezonedatetime-conversiondate

Java Date and utcTimeOffset


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.


Solution

  • 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