Java Data Type How to - Check if a Date is one month ago








Question

We would like to know how to check if a Date is one month ago.

Answer

import static java.lang.System.out;
import static java.util.Calendar.MONTH;
/*w w  w  .j a  v a 2s  .c  o m*/
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
  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/2015")));
    out.println(isBeforeMonths(1, new Date()));
    out.println(isBeforeMonths(-1, sdf.parse("24/12/2015")));
  }

  private static boolean isBeforeMonths(int months, Date aDate) {
    Calendar calendar = Calendar.getInstance();
    calendar.add(MONTH, months);
    return aDate.compareTo(calendar.getTime()) < 0;
  }
}

The code above generates the following result.