Date and Time

converting java.time.localdatetime to java.util.date

Table of Contents

Program

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateLocalTimeToUtilDate {
   public static void main(String[] args) {
      LocalDateTime dateTime = LocalDateTime.now();
      Instant i = dateTime.atZone(ZoneId.systemDefault()).toInstant();
      System.out.println("Instant = "+i);
      java.util.Date date = Date.from(i);
      System.out.println("Date = "+date);
   }
}

Output

Instant = 2021-05-17T11:28:27.592047100Z
Date = Mon May 17 16:58:27 IST 2021 

Description

public static LocalDateTime now()

Obtains the current date-time from the system clock in the default time-zone.
This will query the system clock in the default time-zone to obtain the current date-time.

Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.

Returns:

the current date-time using the system clock and default time-zone, not null

public ZonedDateTime atZone(ZoneId zone)

Combines this instant with a time-zone to create a ZonedDateTime.
This returns a ZonedDateTime formed from this instant at the specified time-zone. An exception will be thrown if the instant is too large to fit into a zoned date-time.

This method is equivalent to ZonedDateTime.ofInstant(this, zone).

Parameters:

zone – the zone to combine with, not null

Returns:

the zoned date-time formed from this instant and the specified zone, not null

public static Date from(Instant instant)

Obtains an instance of Date from an Instant object.
Instant uses a precision of nanoseconds, whereas Date uses a precision of milliseconds. The conversion will trancate any excess precision information as though the amount in nanoseconds was subject to integer division by one million.

Instant can store points on the time-line further in the future and further in the past than Date. In this scenario, this method will throw an exception.

Parameters:

instant – the instant to convert

Returns:

a Date representing the same point on the time-line as the provided instant

Throws:

NullPointerException – if instant is null.
IllegalArgumentException – if the instant is too large to represent as a Date