Java Reference
In-Depth Information
Solution
Utilize a
DateTimeFormatter
to set the format of the specified string of text and
then call on the
LocalDate.parse()
method, passing the string of text as the first
argument and the formatter as the second. The following lines of code demonstrate this
process.
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate yearStart = LocalDate.parse("01/01/2014",
formatter);
How It Works
The
LocalDate
object contains several utility methods that can be used to manipu-
late a date. One such method is
parse()
, which accepts two arguments, a string-
based date and a
DateTimeFormatter
object that specifies the format of the first
argument. This method obtains an instance of
LocalDate
from the text string, and it
returns a
DateTimeParseException
if the text cannot be parsed due to incorrect
formatting.
The ability to obtain a date from a specified string is only one of the nice features
2-7. Performing Date-Time Calculations
Problem
You want to add a number of days or subtract a number of weeks from a given date or
time.
Solution
Utilize the built-in utility methods in the
LocalDate
and
LocalTime
objects to
perform the required calculation. The following code obtains the current date and time
and performs some basic calculations on them.