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 .  co 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 a v  a2s.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
Home » Java Tutorial » Date, Time, Calendar, TimeZone

Date

    Date class
    Date comparison
    Converting date value
    DateFormat class
    Format time
    DateFormat and Locale
    Convert String to Date

Calendar

    Calendar class
    Calendar date time getter
    Calendar set hour,minute,second
    Calendar calculation
    Calendar comparison
    Calendar properties
    GregorianCalendar

TimeZone

    TimeZone
    TimeZone ID and display name
    TimeZone daylight saving

DateFormat

    DateFormat class
    Format time
    DateFormat and Locale
    Convert String to Date
    SimpleDateFormat
    Parse date string into Date object
    SimpleDateFormat day format
    SimpleDateFormat Hour Time format
    SimpleDateFormat format minute
    SimpleDateFormat to format month
    SimpleDateFormat to format second value
    SimpleDateFormat to format TimeZone
    SimpleDateFormat to format year
    SimpleDateFormat to combine formatting flags