Our Java program demonstrates various operations with dates and times using the java.time package, which offers comprehensive support for handling time-related tasks.
To run this program, save it as TimeExample.java, compile it with javac TimeExample.java, and then run it with java TimeExample.
This Java code demonstrates similar functionality to the original example:
We use Instant.now() to get the current time.
We create a specific date and time using ZonedDateTime.of().
We extract various components of the date and time.
We compare two times using isBefore(), isAfter(), and isEqual().
We calculate the duration between two times using Duration.between().
We perform arithmetic on times using plus() and minus().
The main differences are:
Java uses ZonedDateTime instead of a simple time struct.
Duration calculations are done using the Duration class.
Java’s time API is more object-oriented, with methods like toHours() instead of Hours().
This example showcases Java’s robust date and time handling capabilities, which are part of the java.time package introduced in Java 8.