tags:

views:

165

answers:

5

I'm trying an example:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String date = "03/09/2010"; //30 days from today
Date usefullDate = df.parse(date);

Calendar todaysDatePlus30Days = Calendar.getInstance();
todaysDatePlus30Days.add(Calendar.DAY_OF_YEAR, 30);

System.out.println ("Compared Value: " +
usefullDate.compareTo(todaysDatePlus30Days.getTime()))

the printed value is -1. why is it not printing 0?

I think the problem is that todaysDatePlus30Days.getTime() is bringing the actual time as well. whereas usefullDate's time is 00:00:00.

So next question is how can I just get the date?

+3  A: 

The date you parse is implicitly midnight of that date. The one you construct will be the current time of day.

Try:

Calendar todayPlus30 = new GregorianCalendar() {{
  add(Calendar.DAY_OF_YEAR, 30);
  set(Calendar.HOUR_OF_DAY, 0);
  set(Calendar.MINUTE, 0);
  set(Calendar.SECOND, 0);
  set(Calendar.MILLISECOND, 0);
}};

I might have a couple of those constants wrong, and you can do this with Calendar.newInstance() if you like, though the syntax is a little different.

Pointy
Your cause is right on, but you can't subclass a return value like that. You will have to keep a reference and call the sets on that reference, or use `new GregorianCalendar(){{`
Yishai
correct. I had to call sets on the `todayPlus30` object
Omnipresent
Oh right, sorry; I always use GregorianCalendar and I just typed in robot mode :-)
Pointy
+2  A: 

As a further comment, I would investigate JodaTime for all date-related Java work. It's much more intuitive, and doesn't suffer from threading problems in the date/time formatting and parsing classes (unlike the standard Java libraries). Nowadays it's a de facto replacement for the java.util.{Date,Calendar} mess.

e.g. see the LocalDate class and its plusDays() method.

Brian Agnew
+1  A: 

When you System.out.println(..) them, the result is:

Tue Mar 09 00:00:00 EET 2010
Tue Mar 09 20:31:39 EET 2010

So they are not equal - their hours differ. This is because Calendar.getInstance() returns the current date and time.

If you want them to be equal, you'll have to set(..) the hours, minutes and seconds fields to 0.

Bozho
+1  A: 

If you add the following lines to your example, you will learn that useful Date has a different time

System.out.println ("" + usefullDate );
System.out.println ("" + todaysDatePlus30Days.getTime());
stacker
A: 

I suggest using JodaTime, but if you use long for date/time you can do...

long todaysDay = System.currentTimeMillis() / MILLIS_PER_DAY;
long in30days = todaysDay + 30;
long usefulDay = usefulDate.getTime() / MILLIS_PER_DAY;
if (in30days == usefulDay) // days are the same.

Note: the performs calculations as per GMT+0 timezone. This can make a difference.

Peter Lawrey