Java Reference
In-Depth Information
to create a date-time formatter from a given pattern, such as dd/MM/yyyy, or even
programmatically, and how to use this formatter for both parsing and printing a date.
12.2. Manipulating, parsing, and formatting dates
The most immediate and easiest way to create a modified version of an existing LocalDate is
changing one of its attributes, using one of its withAttribute methods. Note that all the methods
return a new object with the modified attribute, as shown in the following listing. They don't
mutate the existing object!
Listing 12.6. Manipulating the attributes of a LocalDate in an absolute
way
You can also do this with the more generic with method, taking a TemporalField as first
argument, as in the last statement of listing 12.6 . This last with method is the dual of the get
method used in listing 12.2 . Both of these methods are declared in the Temporal interface
implemented by all the classes of the Date and Time API, which define a single point in time
such as LocalDate, LocalTime, LocalDateTime, and Instant. More precisely, the get and with
methods let you respectively read and modify the value of a field of a Temporal object. They
throw an Unsupported-TemporalTypeException if the requested field isn't supported by the
specific Temporal, for example, a ChronoField.MONTH_OF_YEAR on an Instant or a
ChronoField.NANO _OF_SECOND on a LocalDate.
It's even possible to manipulate a LocalDate in a declarative manner. For example, you can add
or subtract a given amount of time, as shown in the next listing.
Listing 12.7. Manipulating the attributes of a LocalDate in a relative way
Similarly to what we've explained about the with and get methods, the generic plus method used
in the last statement of listing 12.7 , together with the analogous minus method, is declared in
 
Search WWH ::




Custom Search