In Java 8, you can convert a LocalDateTime
object to a particular format using the DateTimeFormatter
class. Here’s an example:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeFormatExample {
public static void main(String[] args) {
// create a LocalDateTime object
LocalDateTime localDateTime = LocalDateTime.now();
// 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 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. Then we’re using the format()
method to convert the LocalDateTime
object to the desired format. Finally, we’re printing the formatted datetime string.
You can change the pattern to match the desired format you want to convert the LocalDateTime
object to.