Java Reference
In-Depth Information
Representing the Units of Datetime Fields
Time is measured in units such as years, months, days, hours, minutes, seconds, weeks, etc. An instance of the
TemporalUnit
interface in the
java.time.temporal
package represents a unit of time. The
ChronoUnit
in the same
package contains the following constants to represent units of time:
CENTURIES
,
DAYS
,
DECADES
,
ERAS
,
FOREVER
,
HALF_DAYS
,
HOURS
,
MICROS
,
MILLENNIA
,
MILLIS
,
MINUTES
,
MONTHS
,
NANOS
,
SECONDS
,
WEEKS
, and
YEARS
.
The
ChronoUnit
enum implements the
TemporalUnit
interface. Therefore, all constants in the enum are an
instance of the
TemporalUnit
.
■
Constants for some datetime units that are specific to the isO-8601 calendar system are declared in the
IsoFields
class. For example,
IsoFields.QUARTER_YEARS
and
IsoFields.WEEK_BASED_YEARS
represent isO-8601
based a quarter-year (3 months) and a week-based year (52 or 53 weeks), respectively. the isO-8601 standard considers
a seven day period as a week; a week starts on a monday; the first calendar week of the year is the one that includes the
first thursday of the year; the first week of a year may start in the previous year and the last week of a year may end in
the succeeding year. this may result in a 53 weeks in a year. For example, the first week of 2009 started on
December 29, 2008 and the last week on December 29, 2009, making 2009 a 53 week year.
Tip
Datetime classes provide two methods,
minus()
and
plus()
. They take an amount of time and the unit of time
to return a new datetime by subtracting and adding the specified time. Convenience methods such as
minusDays()
,
minusHours()
,
plusDays()
,
plusHours()
, etc. are also provided by the applicable classes to subtract and add time.
The following snippet of code illustrates the use of the
ChronoUnit
enum constants with these methods:
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
...
LocalDateTime now = LocalDateTime.now();
// Get the date time 4 days ago
LocalDateTime ldt2 = now.minus(4, ChronoUnit.DAYS);
// Use the minusDays() method to get the same result
LocalDateTime ldt3 = now.minusDays(4);
// Get date and time 4 hours later
LocalDateTime ldt4 = now.plus(4, ChronoUnit.HOURS);
// Use the plusHours() method to get the same result
LocalDateTime ldt5 = now.plusHours(4);
System.out.println("Current Datetime: " + now);
System.out.println("4 days ago: " + ldt2);
System.out.println("4 days ago: " + ldt3);
System.out.println("4 hours after: " + ldt4);
System.out.println("4 hours after: " + ldt5);