Java Convert LocalDateTime to Date in UTC
Tags: Java LocalDateTime Java Date Java 8 UTC
In this Java core tutorial we learn how to convert a java.time.LocalDateTime object to a java.util.Date in UTC time zone offset.
How to convert LocalDateTime to UTC Date in Java
In Java, with a given LocalDateTime object we can follow these steps to convert it to an UTC Date object.
- Step 1: use the LocalDateTime.toInstant(ZoneOffset offset) method to convert the LocalDateTime object to an Instant object at UTC time zone offset.
- Step 2: use the Date.from(Instant instant) method to instantiate a new Date object from Instant object of step 1.
ConvertLocalDateTimeToUTCDateExample1.java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
public class ConvertLocalDateTimeToUTCDateExample1 {
public static void main(String... args) {
LocalDateTime localDateTime = LocalDateTime.parse("2022-05-29T07:30:20");
// Convert LocalDateTime object to UTC Date object
Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
Date date = Date.from(instant);
System.out.println("LocalDateTime: " + localDateTime);
System.out.println("UTC Date: " + date);
}
}
LocalDateTime: 2022-05-29T07:30:20
UTC Date: Sun May 29 14:30:20 ICT 2022
Happy Coding 😊
Related Articles
Java Convert LocalDate to Date in UTC
Java Convert Date to LocalDate in UTC
Java Convert Date to LocalDateTime in UTC