Java Reference
In-Depth Information
12.1.3. Instant: a date and time for machines
As humans we're used to thinking of dates and time in terms of weeks, days, hours, and minutes.
Nonetheless, this representation isn't easy for a computer to deal with. From a machine point of
view, the most natural format to model time is with a single large number representing a point
on a continuous timeline. This is the approach used by the new java.time.Instant class, which
basically represents the number of seconds passed since the Unix epoch time, set by convention
to midnight of January 1, 1970 UTC.
You can create an instance of this class by passing the number of seconds to its ofEpochSecond
static factory method. In addition, the Instant class supports nanosecond precision. There's a
supplementary overloaded version of the ofEpochSecond static factory method that accepts a
second argument that's a nanosecond adjustment to the passed number of seconds. This
overloaded version adjusts the nanosecond argument, ensuring that the stored nanosecond
fraction is between 0 and 999,999,999. This means all the following invocations of the
ofEpochSecond factory method will return exactly the same Instant:
As you've already seen for the LocalDate and the other human-readable date-time classes, the
Instant class also supports another static factory method named now, which allows you to
capture a timestamp of the current moment. It's important to reinforce that an Instant is
intended for use only by a machine. It consists of a number of seconds and nanoseconds. As a
consequence, it doesn't provide any ability to handle units of time that are meaningful to
humans. For example, this statement
int day = Instant.now().get(ChronoField.DAY_OF_MONTH);
will just throw an exception like
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfMonth
But you can work with Instants by using the Duration and Period classes, which we look at next.
 
Search WWH ::




Custom Search