Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to convert a Date object to LocalDate object in java?
To convert a Date object to LocalDate object in Java −
Convert the obtained date object to an Instant object using the toInstant() method.
Instant instant = date.toInstant();
Create the ZonedDateTime object using the atZone() method of the Instant class.
ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
Finally, convert the ZonedDateTime object to the LocalDate object using the toLocalDate() method.
LocalDate givenDate = zone.toLocalDate();
Example
Following example accepts a name and Date of birth from the user in String formats and converts it to LocalDate object and prints it.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Scanner;
public class DateToLocalDate {
public static void main(String args[]) throws ParseException {
//Reading name and date of birth from the user
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your date of birth (dd-MM-yyyy): ");
String dob = sc.next();
//Converting String to Date
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(dob);
//Converting obtained Date object to LocalDate object
Instant instant = date.toInstant();
ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
LocalDate localDate = zone.toLocalDate();
System.out.println("Local format of the given date of birth String: "+localDate);
}
}
Output
Enter your name: Krishna Enter your date of birth (dd-MM-yyyy): 26-09-1989 Local format of the given date of birth String: 1989-09-26
Advertisements
