Java offers extensive support for dates and times through the java.time package. Here are some examples:
To run the program, compile and execute it using the javac and java commands:
This Java code demonstrates various operations with dates and times, similar to the original example. It uses classes from the java.time package, which provides a comprehensive date-time model for Java.
The LocalDateTime class is used for date-time without a time zone, while ZonedDateTime is used for a date-time with a time zone. The Duration class represents a time-based amount of time.
Methods like isBefore(), isAfter(), and isEqual() are used for comparing times. The plus() and minus() methods are used to add or subtract durations from a date-time.
Note that Java’s date-time API is more explicit about time zones compared to some other languages. When comparing times or calculating durations between times in different time zones, you need to ensure they’re in the same time zone (as done here by converting now to UTC when comparing with then).