To convert a date-time object to a date object, you can use the toLocalDate() method of the LocalDateTime class.
This method was added to Java 8 date-time API. So, can be used in Java 8 and higher versions such as Java 11, Java 17, etc.
The toLocalDate() method returns the date part from the date-time with the same year, month, and day.
For example, if we get the date from the "2022-03-14T17:28:13.048999208", then the result will be "2022-03-14";
Let's understand with the running code examples.
/*
* Code example to convert datetime to date object in Java
*/
import java.time.LocalDateTime;
public class JExercise {
public static void main(String[] args) {
// parse the string date into date time
LocalDateTime date = LocalDateTime.parse("2022-03-14T17:28:13.048999208");
// Displaying date and time
System.out.println("Date Time: "+date);
// Get date only
LocalDate ldate = date.toLocalDate();
// Display result
System.out.println("Date: "+ldate);
}
}
Output:
Date Time: 2022-03-14T17:28:13.048999208
Date: 2022-03-14
Let's see the signature of this method:
public LocalDate toLocalDate()
Package Name: java.time;
Class Name: LocalDateTime
Return Value: It returns a date field from the LocalDateTime object with the same year, month, and day.
Parameters: No
Version: Since 1.8
Let's see some more examples.
You can get the current date from the current date-time object as well. Here, we first used the now() method to get the current date-time and then called the toLocalDate() method.
/*
* Code example to convert datetime to date object in Java
*/
import java.time.LocalDateTime;
public class JExercise {
public static void main(String[] args) {
// parse the string date into date time
LocalDateTime date = LocalDateTime.now();
// Displaying date and time
System.out.println("Date Time: "+date);
// Get date only
LocalDate ldate = date.toLocalDate();
// Display result
System.out.println("Date: "+ldate);
}
}
Output:
Date Time: 2022-07-14T21:48:28.251627300
Date: 2022-07-14
/*
* Code example to convert DateTime to date object in Java
*/
import java.time.LocalDateTime;
public class JExercise {
public static void main(String[] args) {
// Current date time
LocalDateTime date = LocalDateTime.now();
// Displaying date and time
System.out.println("Date Time: "+date);
// Get date only
LocalDate ldate = date.toLocalDate();
// Display result
System.out.println("Date: "+ldate);
// Date 2 days ahead
ldate = date.toLocalDate().plusDays(2);
System.out.println("Date 2 days ahead: "+ldate);
}
}
Output:
Date Time: 2022-07-14T22:09:27.304649900
Date: 2022-07-14
Date 2 days ahead: 2022-07-16
Use this code to get results in a single line of code. If you are a beginner, skip this code.
LocalDateTime.now().toLocalDate()
This code will return a LocalDate object from the current date-time. You just copy and run this code to get the result instantly.