In Java 8, you can convert a LocalDate
object to a specific date-time format by first converting it to a LocalDateTime
object and then using a DateTimeFormatter
object to format it to the desired format.
Here’s an example:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateToDateTimeFormatExample {
public static void main(String[] args) {
// create a LocalDate object
LocalDate localDate = LocalDate.now();
// convert LocalDate to LocalDateTime by adding midnight as time
LocalDateTime localDateTime = localDate.atStartOfDay();
// create a DateTimeFormatter object with the desired format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
// format the LocalDateTime object with the formatter
String formattedDateTime = localDateTime.format(formatter);
// print the formatted datetime string
System.out.println(formattedDateTime);
}
}
In this example, we’re first creating a LocalDate
object with the now()
method. Then we’re converting it to a LocalDateTime
object by adding midnight as the time using the atStartOfDay()
method. We’re then creating a DateTimeFormatter
object with the pattern "dd-MM-yyyy HH:mm:ss"
, which represents the format we want to convert the LocalDateTime
object to. Finally, we’re using the format()
method to convert the LocalDateTime
object to the desired format and printing the formatted datetime string.
You can change the pattern to match the desired format you want to convert the LocalDate
object to.