Java8 java.time.Duration class with examples


java.time.Duration tutorials

java.time.Duration is an object introduced in java8. This is a  measurement to find micro time information between two dates. This measures time in micro and nanoseconds. This is a useful finding period of time between various Date and Time API classes. This is an immutable class, Once created, we can not change its value and thread safety class.

Signature

public final class Duration  
        implements TemporalAmount, Comparable<Duration>, Serializable 

Duration class internally store the two below values
Nanoseconds - which is value less than seconds
Seconds - which is a value greater than seconds.
This is different from OLD API java.util Date which uses milliseconds
getNanos() method - this method used to get the nanoseconds
getSeconds() method- this method to get seconds

How to get the duration of hours/mins/secs/milli/nano between two dates?

This is an example for converting Duration Object to other units using below methods
toNanos()
toMillis()
toMinutes()
toHours()
toDays()
We already saw getNanos() method which is different from toNanos()
getNanos() always return value less than seconds
toNanos() returns full nano seconds of Duration object.

LocalDateTime dateTime = LocalDateTime.of(2017, 1, 1, 0, 0);  
LocalDateTime dateTime1 = LocalDateTime.now();  
System.out.println("Differnce in Nano seconds" + java.time.Duration.between(dateTime, dateTime1).getNano());  
System.out.println("Differnce in Milli seconds" + java.time.Duration.between(dateTime, dateTime1).toMillis());  
System.out.println("Differnce in  seconds" + java.time.Duration.between(dateTime, dateTime1).getSeconds());  
System.out.println("Differnce in  minutes" + java.time.Duration.between(dateTime, dateTime1).toMinutes());  
System.out.println("Differnce in  hours" + java.time.Duration.between(dateTime, dateTime1).toHours());  

Output is

Differnce in Nano seconds644942100  
Differnce in Milli seconds52185645644  
Differnce in  seconds52185645  
Differnce in  minutes869760  
Differnce in  hours14496  

How to add/subtract hours/minutes/seconds for duration in java8?

Duration class provides various methods for adding/substracting nanos, milli,seconds,minutes and days
plusNanos()
plusMillis()
plusSeconds()
plusMinutes()
plusHours()
plusDays()
minusNanos()
minusMillis()
minusSeconds()
minusMinutes()
minusHours()
minusDays()
Please see the method usage with example below

Duration duration = Duration.between(LocalTime.MIDNIGHT,LocalTime.NOON);  
System.out.println(duration.getSeconds());  
duration = duration.plusSeconds(400);  
System.out.println(duration.getSeconds());  
duration = duration.minusSeconds(400);  
System.out.println(duration.getSeconds());  

Output is

43200  
43600  
43200  

Similar Posts