Java: compare dates using Calendar

When it comes to date comparison most of the times calling the .getTime() method from the Date class is enough.
You can just compare the long variables given from the method.
But there are other cases where you want to compare the year or the month between two dates.
Since the getters and setters from the Date class are deprecated you can not do something like this.

    public void testDate()
    {
        Date date = new Date();
        date.setDate(date.getDate()+1);
        
        System.out.println(date.toString());    
    }

However you can use the Calendar class.


    public void testCalender()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        
        calendar.set(Calendar.YEAR, 1999);
        
        System.out.println(calendar.getTime().toString());
    
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(new Date());
        
        System.out.println(calendar1.getTime().toString());
        
        if(calendar1.get(Calendar.YEAR)>calendar.get(Calendar.YEAR)) {
            System.out.println("You changed the first calendar");
        }
    }

Full test case


import java.util.Calendar;
import java.util.Date;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class DateTest extends TestCase {
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public DateTest( String testName ) {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( DateTest.class );
    }
    
    public void testDate()
    {
        Date date = new Date();
        date.setDate(date.getDate()+1);
        
        System.out.println(date.toString());    
    }
    
    public void testCalender()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        
        calendar.set(Calendar.YEAR, 1999);
        
        System.out.println(calendar.getTime().toString());
    
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(new Date());
        
        System.out.println(calendar1.getTime().toString());
        
        if(calendar1.get(Calendar.YEAR)>calendar.get(Calendar.YEAR)) {
            System.out.println("You changed date one");
        }
    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.