Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Convert LocalDate to Java Util Date in UTC



In this article, we will learn how to convert a local date to a java.util.Date in UTC using Java's date and time API.

Problem Statement

Convert the current date, to a java.util.Date object in Coordinated Universal Time (UTC). The goal is to achieve this conversion while ensuring that the resulting java.util.Date object represents the start of the day in UTC for the given LocalDate.

Steps to Convert LocalDate to java.util.Date in UTC

The following are the steps to convert LocalDate to java.util.Date in UTC

  • Step 1: Import the required classes i.e., java.time and java.util .
  • Step 2: Initialize the LocalDate.
  • Step 3: Convert the LocalDate to java.util.Date in UTC by using the atStartOfDay() method and the toInstant(ZoneOffset.UTC) method.
  • Step 4: Print the result.

Example

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.Date;
public class Demo {
    public static void main(String[] args) {
    LocalDate date = LocalDate.now();
    System.out.println("Date = "+date);
    System.out.println("Date (UTC) = "+Date.from(date.atStartOfDay().toInstant(ZoneOffset.UTC)));
    }
}

Output

Date = 2024-07-01
Date (UTC) = Mon Jul 01 00:00:00 GMT 2024

Code Explanation

Initially we will use import statements to bring in the necessary classes from the java.time and java.util packages. The class Demo is defined with a main method, which is the entry point of the application.

We will get the current date and stores it in a LocalDate object named date.

LocalDate date = LocalDate.now();

date.atStartOfDay() returns a LocalDateTime representing the start of the day (midnight) for the given LocalDate.toInstant(ZoneOffset.UTC) converts this local date time to an instant at the UTC time zone. Date.from() converts the Instant to a java.util.Date object.

Date.from(date.atStartOfDay().toInstant(ZoneOffset.UTC))

At the end, we will print the original LocalDate and the converted java.util.Date in UTC to the console.

Updated on: 2024-07-02T10:26:21+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements