How can I parse/format dates with LocalDateTime? (Java 8)

In Java 8 and later, you can use the java.time.LocalDateTime class to represent a date and time without a time zone. To parse a date and time string into a LocalDateTime object, you can use the java.time.format.DateTimeFormatter class.

Here is an example of how to parse a date and time string in the "yyyy-MM-dd HH:mm:ss" format:

String dateTimeString = "2022-07-28 13:14:15";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);

To format a LocalDateTime object as a string, you can use the format() method of the DateTimeFormatter class. Here is an example of how to format a LocalDateTime object in the "yyyy-MM-dd HH:mm:ss" format:

LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateTimeString = dateTime.format(formatter);

The DateTimeFormatter class supports many different date and time formats, and you can specify your own custom format by using special symbols to represent the different components of the date and time (such as the year, month, day, hour, etc.).

For example, the following symbols can be used in a date and time format:

  • yyyy: four-digit year
  • MM: two-digit month (01-12)
  • dd: two-digit day of month (01-31)
  • HH: two-digit hour (00-23)
  • mm: two-digit minute (00-59)
  • ss: two-digit second (00-59)

You can find more information about the available format symbols in the documentation for the java.time.format.DateTimeFormatter class.