Home >Java >javaTutorial >How Can I Parse and Format Dates and Times Using Java 8's LocalDateTime?

How Can I Parse and Format Dates and Times Using Java 8's LocalDateTime?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 20:23:11570browse

How Can I Parse and Format Dates and Times Using Java 8's LocalDateTime?

Parsing and Formatting Dates with LocalDateTime in Java 8

Java 8 introduced the java.time API for enhanced date and time handling. This API includes the LocalDateTime class to represent dates and times without a specific time zone. Here's how to parse dates from strings and format LocalDateTime instances back to strings:

Parsing Date and Time Strings

To parse a date and time string (such as "2014-04-08 12:30") into a LocalDateTime instance, use the static parse() method with a DateTimeFormatter. The formatter specifies the 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 LocalDateTime Instances

To format a LocalDateTime instance back to a string with the same pattern, use the format() method:

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"

Additional Notes

  • Predefined formatters like DateTimeFormatter.ISO_DATE_TIME can be used for common date/time formats (e.g., ISO 8601).
  • The parse() and format() methods are available for other date/time types like LocalDate and ZonedDateTime.

The above is the detailed content of How Can I Parse and Format Dates and Times Using Java 8'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