Home >Java >javaTutorial >How to Parse and Format Dates and Times Using Java's LocalDateTime?

How to Parse and Format Dates and Times Using Java's LocalDateTime?

Barbara Streisand
Barbara StreisandOriginal
2024-12-29 13:14:14378browse

How to Parse and Format Dates and Times Using Java's LocalDateTime?

How to Handle Dates and Times with LocalDateTime

Parsing

Java 8 introduced the java.time API, leveraging LocalDateTime for advanced date and time manipulation. To parse a string (e.g., "2014-04-08 12:30") into a LocalDateTime instance, utilize the LocalDateTime.parse() method, providing a DateTimeFormatter with the desired date/time pattern:

String str = "1986-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

Formatting

Conversely, to format a LocalDateTime instance back to the original string format, employ the format() method in conjunction with the same DateTimeFormatter:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.of(1986, Month.APRIL, 8, 12, 30);
String formattedDateTime = dateTime.format(formatter); // "1986-04-08 12:30"

Commonly Used Formats

The DateTimeFormatter class provides predefined constants for commonly used date/time formats:

String formattedDateTime2 = dateTime.format(DateTimeFormatter.ISO_DATE_TIME); // "1986-04-08T12:30:00"

Availability

Note that the parse() and format() methods are available for all java.time date/time related objects, such as LocalDate or ZonedDateTime.

The above is the detailed content of How to Parse and Format Dates and Times Using Java's LocalDateTime?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn