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 ??
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.
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");
}
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
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.
精彩评论