Java Reference
In-Depth Information
An object of the Duration class represents an amount of time between two instants on the timeline. The
Duration class supports a directed duration. That is, it allows a positive as well as negative duration. Figure 12-1
shows durations with arrows to signify that they are directed durations.
You can create an instance of the Duration class using one of its ofXXX() static factory methods.
// A duration of 2 days
Duration d1 = Duration.ofDays(2);
// A duration of 25 minutes
Duration d2 = Duration.ofMinutes(25);
the toString() method of the instant class returns a textual representation of the Instant in the isO-8601
format yyyy-mm-ddthh:mm:ss.sssssssssZ. the toString() method of the Duration class returns a textual
representation of the duration in ptnhnmns format, where n is the number of hours, minutes, or seconds.
Tip
What can you do with instants and durations? Typically, they are used for recording timestamps and elapsed time
between two events. Two instants can be compared to know whether one occurs before or after other. You can add
(and subtract) a duration to an instant to obtain another instant. Adding two durations results in another duration.
Classes in the Date-Time API are Serializable . You can use Instant to store timestamps in databases.
Instant and Duration classes store second and nanosecond-of-second parts of their values separately. The
Duration class has getSeconds() and getNano() methods, whereas the Instant class has getEpochSecond() and
getNano() methods to get the two values. The following is an example of getting second and nanosecond of an
Instant :
// Get the current instant
Instant i1 = Instant.now();
// Get seconds and nanoseconds
long seconds = i1.getEpochSecond();
int nanoSeconds = i1.getNano();
System.out.println("Current Instant: " + i1);
System.out.println("Seconds: " + seconds);
System.out.println("Nanoseconds: " + nanoSeconds);
(You will get a different output.)
Current Instant: 2014-01-03T17:01:32.261Z
Seconds: 1388768492
Nanoseconds: 261000000
 
 
Search WWH ::




Custom Search