-
Comparing two Dates!
Hello!
I want to allow the user to enter a date (Year/Month/Day) and then compare it with today's date ... if it before,after, or equal ...
I wrote one but I don't know what is wrong with!
Code:
import java.util.*;
public class tt {
public static void main(String args[]) {
Date t = new Date();
GregorianCalendar today = new GregorianCalendar();
System.out.println(today.YEAR+" "+(t.getMonth()+1)+" "+today.DAY);
GregorianCalendar myDate = new GregorianCalendar(2007,12,24);
System.out.println(today.compareTo(myDate)+"\n");
if(today.compareTo(myDate)<0)
System.out.println("Today Date is Lesser than my Date");
else if(today.compareTo(myDate)>0)
System.out.println("Today Date is Greater than my date");
else
System.out.println("Both Dates are equal");
}
}
thanks
-
Re: Comparing two Dates!
This is the same example you posted but better formatted and with no compile errors
Code:
import java.util.GregorianCalendar;
public class Test {
public static void main(String args[]) {
GregorianCalendar today = new GregorianCalendar();
GregorianCalendar myDate = new GregorianCalendar(2007, 12, 24);
System.out.println(today.compareTo(myDate) + "\n");
if (today.compareTo(myDate) < 0) {
System.out.println("Today Date is Lesser than my Date");
} else if (today.compareTo(myDate) > 0) {
System.out.println("Today Date is Greater than my date");
} else {
System.out.println("Both Dates are equal");
}
}
}
You might just want to know that the main reason you're getting incorrect result is because what you are calling today is actually "Now" including the time fragment of the date not just the date itself