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