Java offers extensive support for times and durations; here are some examples.
This Java code demonstrates various operations with dates and times using the java.time package, which was introduced in Java 8.
We start by getting the current time using Instant.now(). Then we create a specific date and time using ZonedDateTime.of().
We can extract various components of a ZonedDateTime such as year, month, day, hour, etc.
The code shows how to compare two time instants using isBefore(), isAfter(), and equals() methods.
We calculate the duration between two time instants using Duration.between(). The Duration class allows us to get the length of the duration in various units like hours, minutes, seconds, and nanoseconds.
Finally, we demonstrate how to add or subtract a duration from a ZonedDateTime.
To run this program, save it as TimeExample.java and use the following commands:
The output will show the current time, the specified time, various components of the time, comparisons between times, the duration between times, and the results of adding and subtracting durations.
Next, we’ll look at the related idea of time relative to the Unix epoch.