Our Java program demonstrates various operations with dates and times using the java.time package. Here’s the full source code:
To run the program, compile it with javac TimeExample.java and then run it with java TimeExample.
This program demonstrates:
Getting the current time using Instant.now().
Creating a specific date and time with ZonedDateTime.of().
Extracting components of a date/time (year, month, day, etc.).
Comparing times using isBefore(), isAfter(), and equals().
Calculating the duration between two times.
Computing durations in various units (hours, minutes, seconds, nanoseconds).
Adding to and subtracting from times using durations.
Note that Java’s java.time package provides a rich set of classes for working with dates, times, and durations. The Instant class represents a point on the time-line, while ZonedDateTime represents a date and time with a time zone. The Duration class is used for representing a span of time.
Next, we’ll look at the related idea of time relative to the Unix epoch.