0

Possible Duplicate:
How to subtract 45 days from from the current sysdate

Hi I am getting the current system date by using

Java.util.Date date = new java.util.Date();

How can i check whether my Date is One month Before date

For example if today is May 22 2011

How can i check if the date is of April 22 2011 ??

Community
  • 1
  • 1

4 Answers4

2

You could use JodaTime. Its DateTime class has a minusMonth-method. Use this to get the date from one month ago and then compare. See the Joda-API for more details.

martin
  • 2,150
  • 1
  • 34
  • 48
1
Calendar cal1 = Calendar.getInstance();
cal1.setTime(theGivenDate);

Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.MONTH, -1);

if ( (cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) &&
     (cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)) &&
     (cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH)) ) {
  System.out.println("Given date " 
    + theGivenDate + " is exactly one month ago from today");
}
Binil Thomas
  • 13,699
  • 10
  • 57
  • 70
0

You can use Joda DateTime [http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html] for this.

DateTime has a method minusMonths(int months), and then you can convert Joda DateTime to java.util.Date

kuriouscoder
  • 5,394
  • 7
  • 26
  • 40
0

Are you aware that many dates will never be "one month before today" according to your definition for month as "calendar month"? For example, since June has only 30 days, the condition will never be true for May 31st.

You may want to change your definition to that commonly used by banks for purposes like calculating interest and deposit terms: a month is considered to be exactly 30 days, independent of calendar dates. So "one month after" May 31st would be June 30th.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720