Problem with Comparing Dates
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Maria_Cysne
Posted On:   Saturday, April 6, 2002 03:29 PM

I need to compare dates based only on day, month and year. The method compareTo from Date API takes into account the time. Does anybody could help me? Date today=new Date(); Date myDate= (....)(); 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"); If I type the same date for today and myDate, today will be greater than myDate because of the time.    More>>

I need to compare dates based only on day, month and year. The method compareTo from Date API takes into account the time. Does anybody could help me?


			
Date today=new Date();
Date myDate= (....)();
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");


If I type the same date for today and myDate, today will be greater than myDate because of the time.

   <<Less

Re: Problem with Comparing Dates

Posted By:   David_Cole  
Posted On:   Saturday, April 6, 2002 09:31 PM

A Date object is actually a time representation.

As stated in the JavaDoc:


The class Date represents a specific instant in time, with millisecond precision.


java.util.Calendar and java.util.GregorianCalendar
are much more adept at handling and manipulating dates.

Here is a simple example of comparing 2 like dates using GregorianCalendar:



//set both calendarA and calendarB to the date:
//April 6th, 2002
Calendar calendarA = new GregorianCalendar(2002,4,6);
Calendar calendarB = new GregorianCalendar(2002,4,6);

if(calendarA.equals(calendarB)) {
System.out.println("Yup..they are equal!");
}
else{
System.out.println("Dang...not equal.");
}


Also take a look at SimpleDateFormat for a nice way to format output of Calendar objects.

Good Luck!

Dave

About | Sitemap | Contact