Michał Ziober Michał Ziober - 1 month ago 5
Java Question

Date earlier than a month ago

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.

Answer Source
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