Java Reference
In-Depth Information
How It Works
As with most programmatic techniques, there is more than one way to perform date
calculations with Java. The Date-Time API includes a few new techniques for determ-
ining time intervals. The new Period class is used to determine the period of differ-
ence between two units for specified objects. To obtain a Period between two date-
time objects, call the Period.between() method, passing the two date-time ob-
jects for which you'd like to obtain the Period . The Period has a number of meth-
ods that can be used to break down the intervals into different units. For instance, the
number days in the period of the two date-time objects can be obtained using the
getDays() method. Similarly, the getMonths() and getYears() methods can
be called to return the number of months or years in the period.
The Date-Time API also includes a ChronoUnit Enum that can be used to work
with calendar systems other than ISO, providing unit-based access to manipulate date
and time. Each of the unit values within the Enum contains a number of methods for
performing manipulations. One such method is between() , which returns a single
unit of time only in the specified unit between the two given date-time objects. In the
solution, it is used to return years and days using ChronoUn-
it.YEARS.between() and ChronoUnit.DAYS.between() , respectively.
One of the most useful techniques is to perform calculations based on the given
date's time in milliseconds. This provides the most accurate calculation because it
works on the time at a very small interval: milliseconds. The current time in milli-
seconds can be obtained from a Calendar object by calling the getTimeInMil-
lis() method against it. Likewise, a Date object will return its value represented in
milliseconds by calling the getTime() method. As you can see from the solution to
this recipe, the first math that is performed is the difference between the given dates in
milliseconds. Obtaining that value and then taking its absolute value will provide the
base that is needed to perform the date calculations. In order to obtain the absolute
value of a number, use the abs() method that is contained in the java.lang.Math
class, shown in the following line of code:
long mill = Math.abs(cal1. getTimeInMillis()
- date1.getTime());
The absolute value will be returned in long format. The TimeUnit enum can be
used in order to obtain different conversions of the date. It contains a number of
Search WWH ::




Custom Search