Java Reference
In-Depth Information
int dayToAdd = 1;
if (dow == DayOfWeek.FRIDAY) dayToAdd = 3;
if (dow == DayOfWeek.SATURDAY) dayToAdd = 2;
return temporal.plus(dayToAdd, ChronoUnit.DAYS);
});
date = date.with(nextWorkingDay);
Another common operation you may want to perform on your date and time objects is printing
them in different formats specific to your business domain. Similarly, you may want to convert
Strings representing dates in those formats into actual date objects. In the next section, we
demonstrate the mechanisms provided by the new Date and Time API to accomplish these
tasks.
12.2.2. Printing and parsing date-time objects
Formatting and parsing is another relevant feature when working with dates and times. The new
java.time.format package is entirely devoted to this purpose. The most important class of this
package is DateTimeFormatter. The easiest way to create a formatter is through its static factory
methods and constants. The constants such as BASIC_ISO_DATE and ISO_LOCAL_DATE are
just predefined instances of the DateTimeFormatter class. All DateTimeFormatters can be used
to create a String representing a given date or time in a specific format. For example, here we
produce a String using two different formatters:
You can also parse a String representing a date or a time in that format to re-create the date
object itself. You can achieve this by using the parse factory method provided by all the classes
of the Date and Time API representing a point in time or an interval:
LocalDate date1 = LocalDate.parse("20140318",
DateTimeFormatter.BASIC_ISO_DATE);
LocalDate date2 = LocalDate.parse("2014-03-18",
DateTimeFormatter.ISO_LOCAL_DATE);
In comparison to the old java.util.DateFormat class, all the DateTimeFormatter instances are
thread-safe. Therefore, you can create singleton formatters, like the ones defined by the
DateTimeFormatter constants, and share them among multiple threads. The
Search WWH ::




Custom Search