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 Date to LocalDate

By Chaitanya Singh | Filed Under: Java Date

In this tutorial, we will see how to convert Date to LocalDate. The java.util.Date represents date, time of the day in UTC timezone and java.time.LocalDate represents only the date, without time and timezone.

java.util.Date - date + time of the day + UTC time zone
java.time.LocalDate - only date

Keeping these points in mind, we can convert the Date to Local in the following steps:
1. Convert Date to Instant – because we do not want the time in the LocalDate
2. Get the default timezone – because there is no timezone in LocalDate
3. Convert the date to local date – Instant + default time zone + toLocalDate() = LocalDate

Date to LocalDate conversion

import java.time.LocalDate;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;
public class Example {
   public static void main(String[] args) {
	//Getting the current date
	Date date = new Date();
	System.out.println("Date is: "+date);
		
	//Getting the default zone id
	ZoneId defaultZoneId = ZoneId.systemDefault();
		
	//Converting the date to Instant
	Instant instant = date.toInstant();
		
	//Converting the Date to LocalDate
	LocalDate localDate = instant.atZone(defaultZoneId).toLocalDate();
	System.out.println("Local Date is: "+localDate);
   }
}

Output:

Date is: Sun Oct 22 21:33:46 IST 2017
Local Date is: 2017-10-22

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