> As the subject state. I have a problem which is to
> show all objects whose date (java.util.Date) is within a month of the
> current date.
You haven't really defined your problem enough. Is that all dates within 30 days, 31 days, 28 days? Or are you saying that if it is the 5th of Feb, then I'm interested in all before 5th of March?
You can use the java.util.Calendar class to do date "arithmetic" and then getDate objects which you can compare... Post some code and we'll help you
I agree in the brief reply above.
Past or future? The following method tests if a date is between today (say, Sept 8) and a month later (say, October 8, inclusive). Go ahead and modify it to your needs.
public static boolean withinAMonth(Date d)
{ Calendar thisDayOfMonth = new GregorianCalendar(); // today
Calendar test = new GregorianCalendar();
test.setTime(d);
if (thisDayOfMonth.get(Calendar.YEAR) == test.get(Calendar.YEAR)
&& thisDayOfMonth.get(Calendar.MONTH) == test.get(Calendar.MONTH)
&& thisDayOfMonth.get(Calendar.DAY_OF_MONTH) <= test.get(Calendar.DAY_OF_MONTH))
// later this month
{ return true;
}
thisDayOfMonth.add(Calendar.MONTH, 1); // go to same day next month
return thisDayOfMonth.get(Calendar.YEAR) == test.get(Calendar.YEAR)
&& thisDayOfMonth.get(Calendar.MONTH) == test.get(Calendar.MONTH)
&& thisDayOfMonth.get(Calendar.DAY_OF_MONTH) >= test.get(Calendar.DAY_OF_MONTH);
}
I know I'm reviving an old thread now. I just happened to look at my code again and think it was unnecessarily complicated. So here's a new attempt (not thoroughly tested):
public static boolean withinAMonth(Date d)
{
// System.out.println(DateFormat.getDateInstance().format(d));
Calendar thisDayOfMonth = new GregorianCalendar(); // today
Calendar test = new GregorianCalendar();
test.setTime(d);
if (test.before(thisDayOfMonth))
{ return false;
}
thisDayOfMonth.add(Calendar.MONTH, 1); // go to same day next month
return ! test.after(thisDayOfMonth);
}