Code for Comparing two dates in Java , Get date from keyborad and Compare

We can compare two dates in Java in the following ways

Ist Method :
-----------

Steps:
-----
1) Get two dates in the format of dd/mm/yyyy as a string.
2) Convert the Dates String to Date format using DateFormat Class.
3) Now Compare the two dates.

The following code is used to compare two dates , wheather it is equal , greater or Less than the other date.

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

public class DateCheck {
public static void main(String [] args){
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
DateFormat df = new SimpleDateFormat ("dd/MM/yyyy");
System.out.println("Enter any Date1");
String dateSt1= br.readLine();
System.out.println("Enter any Date2");
String dateSt2= br.readLine();
Date date1=df.parse(dateSt1);
Date date2=df.parse(dateSt2);
if(date1.equals(date2))
{
System.out.println("Both Dates are equal");
}
else if(date1.before(date2))
{
System.out.println("Date1 is greater than Date2");
}

else
{
System.out.println("Date2 is greater than date1");
}

}
catch(Exception e){
System.out.println("Error");
}
}
}


II) Method II
---------

Steps :

1) Get two dates as day , month , year
2) Covert into Date format using Calender Class set method
3) Compare 2 dates.

import java.util.*;
import java.text.*;
import java.io.*;
public class DateCheckCal{
public static void main(String args[]){

Calendar cal = Calendar.getInstance();
Calendar today = Calendar.getInstance();
String day="";
String month="";
String year="";

try{

BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));

System.out.println("Enter the Day in number (from 1 to 31)");
day= br.readLine();

System.out.println("Enter the Month in number (from 0 to 11) ");
month= br.readLine();

System.out.println("Enter the Month in number (eg. 1999)");
year= br.readLine();
} catch (Exception e)
{
}


cal.set(Integer.parseInt(year) , Integer.parseInt(month)-1, Integer.parseInt(day),12,0,0 ); // Month starts from 0. Set Time to is 12:00:00 for both date

today.set(today.get(Calendar.YEAR),today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH), 12,0,0);

if(cal.before(today)) System.out.print("Today (" + new SimpleDateFormat("dd/MM/yyyy").format(today.getTime()) + ") is greater than the input date " + new
SimpleDateFormat("dd/MM/yyyy").format(cal.getTime()));

else if(cal.after(today)) System.out.print("Today(" + new SimpleDateFormat("dd/MM/yyyy").format(today.getTime()) + ") is less than the input date " + new
SimpleDateFormat("dd/MM/yyyy").format(cal.getTime()));

else
System.out.print("Both dates are equal.");
}
}

0 comments:

Post a Comment

 
Copyright 2011 Java Online