beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Convert LocalDate to Date

By Chaitanya Singh | Filed Under: Java Date

In this guide, we will see how to convert LocalDate to Date. Before we see the code for the conversion, lets see what’s the difference between Date and LocalDate.

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

So to convert the LocalDate to Date, we must append the time and timezone info with the date. Keeping this in mind, the steps for the conversion are as follows:

1. Getting the default time zone so we can append the timezone info with the date
2. Calling atStartOfDay() so that we can append the time with the date
3. LocalDate to Date – local date + atStartOfDay() + default time zone + toInstant() = Date

LocalDate to Date conversion

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
public class Example {
   public static void main(String[] args) {
	//default time zone
	ZoneId defaultZoneId = ZoneId.systemDefault();
		
	//creating the instance of LocalDate using the day, month, year info
        LocalDate localDate = LocalDate.of(2016, 8, 19);
        
        //local date + atStartOfDay() + default time zone + toInstant() = Date
        Date date = Date.from(localDate.atStartOfDay(defaultZoneId).toInstant());
        
        //Displaying LocalDate and Date
        System.out.println("LocalDate is: " + localDate);
        System.out.println("Date is: " + date);
   }
}

Output:

LocalDate is: 2016-08-19
Date is: Fri Aug 19 00:00:00 IST 2016

Related Posts:

  1. Java LocalDate
  2. Java – Convert Date to LocalDate

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Date and Time

  • Java Date Time
  • Java LocalDate
  • Java LocalTime
  • Java LocalDateTime
  • Java ZonedDateTime
  • Java DateTimeFormatter
  • current date time

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap