Java Reference
In-Depth Information
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate ld3 = LocalDate.parse(input, formatter);
System.out.println("Custom Parsed Date: " + ld3);
} catch (DateTimeParseException ex){
System.out.println("Not parsable: " + ex);
}
Here is the result:
Parsed Date: 2014-12-28
Parsed Date-Time: 2014-12-28T08:44
Different Parser: 2014-12-28
Custom Parsed Date: 2014-12-28
How It Works
The temporal classes of the Date-Time API include a
parse()
method, which can be
used to parse a given input string using a specified format. By default, the
parse()
method will format based on the target object's default
DateTimeFormatter
. For
example, to parse the string
"2014-01-01"
, the default
LocalDate.parse()
method can be called.
LocalDate date = LocalDate.parse("2014-01-01");
However, another
DateTimeFormatter
can be specified as a second argument
to the
parse()
method.
DateTimeFormatter
is a final class used for formatting
and printing dates and times. It contains a number of built-in formatters that can be
specified to coerce strings into date-time objects. For example, to parse based on the
standard
ISO_DATE
format without offset, call
DateTimeFormat-
ter.ISO_DATE
, as demonstrated in the solution to this recipe. For more information
Oftentimes, it is necessary to parse strings of text into date-time objects. Such tasks
are made easy with the
parse()
method being built into many of the core date-time
classes.