Write a Java Program to Create a LocalDate object from the object of Date class


This Java program converts a Date object to a LocalDate object using the java.time package. It creates a Date object representing the current date and time using the new Date() constructor. It then uses the toInstant() method of the Date object to obtain an Instant object representing the same date and time. The atZone() method is called with the ZoneId.systemDefault() method to convert the Instant object to a ZonedDateTime object using the default time zone of the system. Finally, the toLocalDate() method is called on the ZonedDateTime object to obtain a LocalDate object representing the date without time information.

  • import java.io.*;: This imports the java.io package, which contains classes for input and output operations.
  • import java.time.*;: This imports the java.time package, which contains classes for working with dates, times, and durations.
  • import java.util.Date;: This imports the java.util.Date class, which is used to obtain the current date and time.
  • class LocalDate_Object: This defines a class named LocalDate_Object.
  • public static void main(String args[]): This is the entry point of the program. It declares a public static method named main that takes an array of strings as an argument.
  • Date date = new Date();: This creates a new Date object representing the current date and time.
  • LocalDate ld = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();: This converts the Date object to a LocalDate object. First, the toInstant() method is called on the Date object to obtain an Instant object representing the same date and time. Then, the atZone() method is called with the ZoneId.systemDefault() method to obtain a ZonedDateTime object representing the same date and time using the default time zone of the system. Finally, the toLocalDate() method is called on the ZonedDateTime object to obtain a LocalDate object representing the date without time information.
  • System.out.println("LocalDate : " + ld); : This prints the string "LocalDate : " followed by the LocalDate object ld. This date is represented as a string, which is then printed to the console.

Overall, this program converts the current date and time represented as a Date object to a LocalDate object, and then prints the date without time information to the console.

Source Code

import java.io.*;
import java.time.*;
import java.util.Date;
class LocalDate_Object
{
	public static void main(String args[])
	{
		Date date = new Date();
		LocalDate ld = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
		System.out.println("LocalDate : " + ld);
	}
}

Output

LocalDate : 2022-12-17

Example Programs