Calendar comparison

In this chapter you will learn:

  1. What are the methods available for comparing two Calendar objects
  2. Compare date time using after method
  3. Compare date time using before method

Compare two Calendar values

We can use the following methods to compare two Calendar objects.

  • boolean after(Object when)
    Returns whether this Calendar represents a time after the time represented by the specified Object.
  • boolean before(Object when)
    Returns whether this Calendar represents a time before the time represented by the specified Object.
  • int compareTo(Calendar anotherCalendar)
    Compares the time values (millisecond offsets from the Epoch) represented by two Calendar objects.
  • boolean equals(Object obj)
    Compares this Calendar to the specified Object.

Compare date time using after method

The following code shows how to compare date time using after method.

import java.util.Calendar;
//  j a  v  a  2s.c  o  m
public class Main {
  public static void main(String[] args) {

    Calendar future = Calendar.getInstance();
    future.set(Calendar.YEAR, 3010);
    
    Calendar now = Calendar.getInstance();
    
    System.out.println("Is futureCal after now ? : " + future.after(now));
  }
}

The output:

Compare date time using before method

To compare date time using before method:

import java.util.Calendar;
/*j ava 2  s .  c o m*/
public class Main {
  public static void main(String[] args) {
    Calendar old = Calendar.getInstance();
    old.set(Calendar.YEAR, 1990);
 
    Calendar now = Calendar.getInstance();
    
    System.out.println("Is old before now ? : " + old.before(now));
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. whether date/time interpretation is to be lenient
  2. Get the available locales