Java Reference
In-Depth Information
The
DateTimeFormatter
class contains several
parse()
methods to facilitate parsing of strings into datetime
objects. The
DateTimeFormatter
class does not know the type of datetime object that can be formed from the strings.
Therefore, most of them return a
TemporalAccessor
object that you can query to get the datetime components. You
can pass the
TemporalAccessor
object to the
from()
method of the datetime class to get the specific datetime object.
The following snippet of code shows how to parse a string in MM/dd/yyyy format using a DateTimeFormatter object
to construct a
LocalDate
:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
...
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
TemporalAccessor ta = formatter.parse("01/10/2014");
LocalDate ld = LocalDate.from(ta);
System.out.println(ld);
2014-01-10
Another version of the
parse()
method takes a
TemporalQuery
that can be used to parse the string directly
into a specific datetime object. The following snippet of code uses this version of the
parse()
method. The second
parameter is the method reference of the
from()
method of the
LocalDate
class. You can think of the following
snippet of code as shorthand for the above code:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate ld = formatter.parse("01/10/2014", LocalDate::from);
System.out.println(ld);
2014-01-10
The DateTimeFormatter class contains a
parseBest()
method. Using this method needs little explanation. Suppose
you receive a string as an argument to a method. The argument may contain varying pieces of information for date and
time. In such a case, you want to parse the string using the most pieces of information. Consider the following pattern:
yyyy-MM-dd['T'HH:mm:ss[Z]]
The above pattern has two optional sections. A text with this pattern may be fully parsed to an
OffsetDateTime
,
and partially parsed to a
LocalDateTime
and a
LocalDate
. You can create a parser for this pattern as
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd['T'HH:mm:ss[Z]]");
The following snippet of code specifies
OffsetDateTime
,
LocalDateTime
, and
LocalDate
as the preferred parsed
result types:
String text = ...
TemporalAccessor ta = formatter.parseBest(text,
OffsetDateTime::from,
LocalDateTime::from,
LocalDate::from);