Pages

Thursday, December 3, 2020

Java – Convert LocalDate to Date

1. Overview

In this tutorial, We'll learn how to convert Java 8 LocalDate to util Date. Before jumping into the example programs let us understand the core difference between Date and LocalDate classes.

Date - java.util.Date - date + time + timezone
LocalDate - java.time.Localdate - date only

Java util date store the date and time but does not store the timezone. When we print the timezone it just takes the system timezone where as LocalDate is added in java 8 api and it stores the only date part without time part.

Java – Convert LocalDate to Date


2. Convert LocalDate To Date in Java

Understand the steps needed to write the code

Steps:

Step 1: First Create the LocalDate object using either now() or of() method. now() method gets the current date where as of() creates the LocalDate object with the given year, month and day.

Step 2: Next, Get the timezone from operating system using ZoneId.systemDefault() method.

Step 3: Additionally, Call LocalDate.atStartOfDay() method with timezone as parameter and it returns ZonedDateTime.

Step 4: Finally, Call Date.from(zonedDateTime.toInstant()) method and pass the Instant object from zoned date time.toInstant() method. This from() method returns the util Date object.

package com.javaprogramto.java8.dates.conversion.dateto;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

/**
 * Example to convert java.time.LocalDate to java.util.Date.
 * 
 * @author javaprogramto.com
 */
public class LocalDateToDateExample {

	public static void main(String[] args) {

		// Creating the LocalDatetime object
		LocalDate currentLocalDate = LocalDate.now();
		
		// Getting system timezone
		ZoneId systemTimeZone = ZoneId.systemDefault();
		
		// converting LocalDateTime to ZonedDateTime with the system timezone
		ZonedDateTime zonedDateTime = currentLocalDate.atStartOfDay(systemTimeZone);
		
		// converting ZonedDateTime to Date using Date.from() and ZonedDateTime.toInstant()
		Date utilDate = Date.from(zonedDateTime.toInstant());
		
		// Printing the input and output dates
		System.out.println("LocalDate  : "+currentLocalDate);
		System.out.println("Util Date : "+utilDate);

	}
}

Output:

LocalDate  : 2020-12-03
Util Date : Thu Dec 03 00:00:00 IST 2020


3. Conclusion

In this article, We've seen converting the LocalDate to Date in java 8 with example program.

GitHub

No comments:

Post a Comment

Please do not add any spam links in the comments section.