October 4, 2023

How to compare dates in Java

This article shows few examples to compare two dates in Java. Updated with Java 8 examples. For the legacy java.util.Date, we can use compareTo, before(), after() and equals() to compare two dates. For the legacy java.util.Calendar, the Calendar works the same way as java.util.Date. And The Calendar contains the similar compareTo, before(), after() and equals() to compare two calender. For the new Java 8 java.time.* classes, all contains similar compareTo, isBefore(), isAfter() and isEqual() to compare two dates, and it works the same way.

How to compare dates in Java Read More

Java 8 – Convert Date to LocalDate and LocalDateTime

Few examples to convert classic Date to Java Time dates and vice versa: Convert java.util.Date to java.time.LocalDate, Convert java.util.Date to java.time.LocalDateTime, Convert java.util.Date to java.time.ZonedDateTime. The java.util.Date has no concept of time zone, and only represents the number of seconds passed since the Unix epoch time. The new Java 8 java.time.Instant is the equivalent class to the classic java.util.Date. The idea of the date conversion is to convert to an instant with a time zone.

Java 8 – Convert Date to LocalDate and LocalDateTime Read More

Java – How to get current date time

In this tutorial, we will show you how to get the current date time from the new Java 8 java.time.* like Localdate, LocalTime, LocalDateTime, ZonedDateTime, Instant and also the legacy date time APIs like Date and Calendar. In summary, For new Java 8 java.time.* APIs , we can use .now() to get the current date-time and format it with DateTimeFormatter. For legacy date-time APIs, we can use new Date() and Calendar.getInstance() to get the current date-time and format it with SimpleDateFormat.

Java – How to get current date time Read More