import java.time.*;
import java.time.temporal.ChronoUnit;
class Demo {
void example() {
// Duration — based on seconds
Duration d = Duration.ofMinutes(5);
System.out.println(d.toMillis()); // 300000
System.out.println(d.plusSeconds(30)); // PT5M30S
// Difference between two Instants
Instant start = Instant.now();
// ... work ...
Instant end = Instant.now();
Duration elapsed = Duration.between(start, end);
System.out.println(elapsed.toMillis() + " ms");
// Period — calendar units
Period p = Period.ofYears(1).plusMonths(2).plusDays(3);
LocalDate then = LocalDate.now().plus(p);
// Difference between dates
LocalDate birth = LocalDate.of(1990, 5, 15);
LocalDate now = LocalDate.now();
Period age = Period.between(birth, now);
System.out.printf("%d years, %d months%n", age.getYears(), age.getMonths());
// Total days between (use ChronoUnit, not Period for this)
long totalDays = ChronoUnit.DAYS.between(birth, now);
System.out.println(totalDays + " days");
}
}
Create a free account and build your private vault. Share publicly whenever you want.