Friday, August 28, 2009

Comparing Dates in Java

Java Provides class called Calendar. One can create instance of Calendar using  Calendar.getInstance():

Setting Default Date in Java :
Calendar.set(2000, Calendar.JUNE, 29) - sets the default date to the calendar passing three arguments like year, month and day.

How to check First Date is before of Second Date :
cal.before(currentcal):
it Returns a boolean value true, if the date mentioned for the cal object is previous date of the mentioned date for the currentcal object of the Calendar class, otherwise it returns the boolean value false.

How to check First Date is after of Second Date :
cal.after(currentcal):
It Returns a booean value true, if the date mentioned for the cal object is later date from the mentioned date for the currentcal object of the Calendar class, otherwise it returns the boolean value false.


Define Date Formate using Java :
new SimpleDateFormat("dd/MM/yyyy"):
It creates instance of the SimpleDateFormat class of the java.text.*; package. It specifies the format for the date. The format is mentioned in the constructor of the SimpleDateFormat class which is the String type argument.

SimpleDateFormat.format(date) - formats the date in the specified format.

Calendar.getTime() - returns the default date in time.

Java Program For Comparing Dates :

package com.anuj.utils;

import java.util.*;
import java.text.*;

public class CompareDate {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        Calendar currentcal = Calendar.getInstance();
        cal.set(2000, Calendar.JUNE, 29);
        
        currentcal.set(currentcal.get(Calendar.YEAR),
                currentcal.get(Calendar.MONTH),
                currentcal.get(Calendar.DAY_OF_MONTH));
        
        if (cal.before(currentcal))
            System.out.print("Current date("
                    + new SimpleDateFormat("dd/MM/yyyy").format(currentcal
                            .getTime()) + ") is greater than the given date "
                    + new SimpleDateFormat("dd/MM/yyyy").format(cal.getTime()));
        else if (cal.after(currentcal))
            System.out.print("Current date("
                    + new SimpleDateFormat("dd/MM/yyyy").format(currentcal
                            .getTime()) + ") is less than the given date "
                    + new SimpleDateFormat("dd/MM/yyyy").format(cal.getTime()));
        else
            System.out.print("Both date are equal.");
    }}

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/