Converting local time to UTC is crucial when building an application which is used by users thought the world, particularly for accurate time calculations and data storage. In this article, we will see the step-by-step procedure of how to convert the local time to UTC using the datetime class in Java.

What is the local time & UTC?

Let us first try to understand what is a local timezone. For example, if I am using an application in California, United States the local timezone is Pacific time (Pacific Standard Time or Pacific daylight time). For India, it is IST (India standard time).

When processing the dates in the server, we need to have a common date format in the database else it would lead to unnecessary confusion.

So, all the different datetime zones are converted to UTC format (Universal time coordinated) and stored in the server.

Using ZonedDateTime and ZoneOffset

Java provides the ZonedDateTime class in the java.time package, which allows us to represent a date and time along with its associated timezone. Additionally, the ZoneOffset class enables us to calculate the offset between timezones. Here’s an example that demonstrates how to convert local time to UTC format.

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class LocalToUTCConverter {
    public static void main(String[] args) {
        // Get the current local time
        LocalDateTime localDateTime = LocalDateTime.now();

        // Get the local timezone
        ZoneId localZoneId = ZoneId.systemDefault();

        // Convert local time to UTC
        ZonedDateTime localDateTimeWithZone = ZonedDateTime.of(localDateTime, localZoneId);
        ZonedDateTime utcDateTime = localDateTimeWithZone.withZoneSameInstant(ZoneId.of("UTC"));

        // Format the UTC datetime as per desired pattern
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = utcDateTime.format(formatter);

        // Print the converted UTC datetime
        System.out.println("UTC Datetime: " + formattedDateTime);
    }
}

In the above example, we obtained the local time from the user using the LocalDateTime.now() and the local timezone using the ZoneId.systemDefault().

We then create a ZonedDateTime object, localDateTimeWithZone, by combining the local time and its associated timezone and converting this ZonedDateTime object to the UTC timezone using withZoneSameInstant(ZoneId.of("UTC")).

To format the converted UTC datetime according to a specific pattern, we use the DateTimeFormatter class and its ofPattern() method. we used the pattern “yyyy-MM-dd HH:mm:ss” in the above example.

Finally, we print the converted UTC datetime to the console.

It should be noted that Java’s ZonedDateTime class automatically adjusts for daylight saving time based on the specified timezones.

FAQ:

Q: Can I convert any local time to UTC format using this approach?

A: Yes, the provided approach can convert any local time to UTC format by considering the offset between the local timezone and UTC.

Q: Does Java automatically handle daylight saving time adjustments during the conversion?

A: Yes, Java’s ZonedDateTime class takes daylight saving time adjustments into account, ensuring accurate conversions even when transitioning between standard time and daylight saving time.

Q: Can I specify a different output format for the converted UTC datetime?

A: Yes, you can modify the DateTimeFormatter pattern in the code snippet to format the converted UTC datetime according to your desired output format.

References:

https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

Categorized in:

Tagged in: