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
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!