How to check whether the given date is earlier than a month ago? What is the fastest algorithm? I have to take into account that different months have different numbers of days.
+5
A:
Calendar calendar = Calendar.getInstance();
calendar.add( Calendar.MONTH , -1 );
return aDate.compareTo( calendar.getTime() ) < 0;
EDIT
Sample test:
import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import static java.lang.System.out;
import static java.util.Calendar.MONTH;
public class BeforeTest {
public static void main( String [] args ) throws java.text.ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
out.println( isBeforeMonths( -1 , sdf.parse("14/12/2009")));
out.println( isBeforeMonths( -1 , new Date() ));
out.println( isBeforeMonths( -1 , sdf.parse("24/12/2009")));
}
private static boolean isBeforeMonths( int months, Date aDate ) {
Calendar calendar = Calendar.getInstance();
calendar.add( MONTH , months );
return aDate.compareTo( calendar.getTime() ) < 0;
}
}
Prints
true
false
false
OscarRyz
2010-01-15 22:56:19
+4
A:
Using Joda Time:
DateTime dt1 = new DateTime(); //Now
DateTime dt2 = new DateTime(2009,9,1,0,0,0,0); //Other date
if (dt1.plusMonths(-1) > dt2) {
//Date is earlier than a month ago
}
Vinko Vrsalovic
2010-01-15 23:00:37