Search code examples
javahtmldateutclocaldatetime

JAVA convert local time (GMT+8) to UTC time


I want to convert datetime-local which is from html to UTC time:

html:

<label>Start Time:</label><input type="datetime-local" name="start_time" />

java:

request.getParameter("start_time") // print out ex:2021-01-07T10:42

that is local time(GMT+8), and I want to convert it to UTC string time

ex: convert to -> 2021-01-07T02:42

I search much resource but still not understand how to do.


Solution

  • java.time through ThreeTen Backport

    java.time is the modern Java date and time API. I recommend that we use it for our date and time work. It was the successor of Joda-Time and came out with Java 1.8 in 2014. It has also been backported to Java 1.6 and 1.7 in the ThreeTen Backport. Using ThreTen Backport we may do:

        String startTime = "2021-01-07T10:42";
        OffsetDateTime utcTime = LocalDateTime.parse(startTime)
                .atZone(ZoneId.systemDefault())
                .toOffsetDateTime()
                .withOffsetSameInstant(ZoneOffset.UTC);
        System.out.println(utcTime);
    

    I ran this code on Java 1.7 in Asia/Shanghai time zone (at offset +08:00). Then the output is:

    2021-01-07T02:42Z

    The time agrees with what you wanted. And it’s in UTC, denoted by the trailing Z.

    If you want to make explicit which time zone to convert from, instead of ZoneId.systemDefault() use something like ZoneId.of("Asia/Hong_Kong"). It’s better to give the relevant time zone ID in the region/city format than a mere GMT offset.

    Why would you want to use an external library for your conversion? java.time is the future-proof library for date and time. Once you move on to Java 8, 9, 10, 11, 12, 13, 14, 15, 16 or later, change your imports to use the built-in java.time, test again and your code is top modern. Note how the code is explicit about converting to UTC, there’s no surprise what’s going on. java.time is so nice to work with.

    Links