Java Reference
In-Depth Information
LocalDate ld = LocalDate.of(2014, 12, 25);
String pattern = "'Christmas in' yyyy 'is on' EEEE";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
String str = ld.format(formatter);
System.out.println(str);
Christmas in 2014 is on Thursday
Parsing Dates and Times
Parsing is the process of creating a date, time, or datetime object from a string. Like formatting, parsing is also handled
by a
DateTimeFormatter
. Please refer to the previous section, “Formatting Dates and Times,” for details on how to get
an instance of the
DateTimeFormatter
class. The same symbols used for formatting are also used as parsing symbols.
There are two ways to parse a string into a datetime object:
•
Using the
parse()
method of the datetime class
parse()
method of the
DateTimeFormatter
class
•
Using the
■
a
DateTimeParseException
is thrown if the text cannot be parsed. it is a runtime exception. the class contains
two methods to provide the error details. the
getErrorIndex()
method returns the index in the text where the error
occurred. the
getParsedString()
method returns the text being parsed. it is good practice to handle this exception
while parsing a datetime.
Tip
Each datetime class has two overloaded versions of the
parse()
static method. The return type of the
parse()
method is the same as the defining datetime class. The following are the two version of the
parse()
method in
LocalDate
class:
static LocalDate parse(CharSequence text)
•
static LocalDate parse(CharSequence text, DateTimeFormatter formatter)
The first version of the
parse()
method takes the textual representation of the datetime object in ISO format.
For example, for a
LocalDate
, the text should be in the yyyy-mm-dd format. The second version lets you specify a
DateTimeFormatter
. The following snippet of code parses two strings into two
LocalDate
objects:
•
// Parse a LocalDate in ISO format
LocalDate ld1 = LocalDate.parse("2014-01-10");
// Parse a LocalDate in MM/dd/yyyy format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate ld2 = LocalDate.parse("01/10/2014", formatter);
System.out.println("ld1: " + ld1);
System.out.println("ld2: " + ld2);
ld1: 2014-01-10
ld2: 2014-01-10