Java offers extensive support for dates and times through the java.time package. Here are some examples:
This Java code demonstrates various operations with dates and times:
We start by getting the current time using Instant.now().
We create a specific date and time using ZonedDateTime.of().
We extract various components of the date and time (year, month, day, etc.).
We demonstrate how to get the day of the week.
We compare two times using isBefore(), isAfter(), and equals().
We calculate the duration between two times using Duration.between().
We show how to get the duration in different units (hours, minutes, seconds, nanoseconds).
Finally, we demonstrate how to add or subtract a duration from a date/time.
To run this program, save it as TimeExample.java, compile it with javac TimeExample.java, and then run it with java TimeExample.
The output will vary depending on the current time when you run the program, but it will show the current time, the specified time (November 17, 2009), various time components, comparisons, and duration calculations.
Next, we’ll look at the related idea of time relative to the Unix epoch.