snippetjavaCritical
How can I parse/format dates with LocalDateTime? (Java 8)
Viewed 0 times
localdatetimewithhowparsejavacanformatdates
Problem
Java 8 added a new java.time API for working with dates and times (JSR 310).
I have date and time as string (e.g.,
After I finished working with the
I have date and time as string (e.g.,
"2014-04-08 12:30"). How can I obtain a LocalDateTime instance from the given string?After I finished working with the
LocalDateTime object: How can I then convert the LocalDateTime instance back to a string with the same format as shown above?Solution
Parsing date and time
To create a
Formatting date and time
To create a formatted string out a
Note that there are some commonly used date/time formats predefined as constants in
The
To create a
LocalDateTime object from a string you can use the static LocalDateTime.parse() method. It takes a string and a DateTimeFormatter as parameter. The DateTimeFormatter is used to specify 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 date and time
To create a formatted string out a
LocalDateTime object you can 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"Note that there are some commonly used date/time formats predefined as constants in
DateTimeFormatter. For example: Using DateTimeFormatter.ISO_DATE_TIME to format the LocalDateTime instance from above would result in the string "1986-04-08T12:30:00".The
parse() and format() methods are available for all date/time related objects (e.g. LocalDate or ZonedDateTime)Code Snippets
String str = "1986-04-08 12:30";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);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"Context
Stack Overflow Q#22463062, score: 790
Revisions (0)
No revisions yet.