What is the method for comparing times in Java?

In Java, you can compare time using the classes java.util.Date and java.util.Calendar.

  1. Date class in Java’s util package
  2. determine if one item is less than, equal to, or greater than another item
  3. Compare()
Date date1 = new Date();
Date date2 = new Date();

int result = date1.compareTo(date2);

如果result的值为0,则表示两个日期相等;如果result的值小于0,则表示date1早于date2;如果result的值大于0,则表示date1晚于date2。

  1. Calendar class in Java
  2. find the difference between two things
  3. schedule
  4. Get the current date and time.
  5. A tool used for organizing events and keeping track of dates.
  6. Compare two objects.
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

int result = cal1.compareTo(cal2);

Similar to the compareTo() method in the Date class, the value of result represents the result of comparing two dates.

Furthermore, you can also use the before() and after() methods to determine if one date is earlier or later than another date.

if (date1.before(date2)) {
    // date1早于date2
}

if (date1.after(date2)) {
    // date1晚于date2
}

The return values of these methods are all of boolean type.

bannerAds