tags:

views:

274

answers:

3

In java, how can I find out if a specific date is within 1 year of today's date.

I have the following but not sure if this is the best approach.

    String date = "01/19/2005";
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date lastExamTakenDate = null;
    Calendar todaysDateMinus1Year = Calendar.getInstance();
    todaysDateMinus1Year.add(Calendar.YEAR, -1);

    if (date!=null)
    {
        try {
             lastExamTakenDate = df.parse(date);
            if (lastExamTakenDate.before(todaysDateMinus1Year.getTime()))
                hasToTakeExam = true;
        } catch (ParseException ex) {
            //exception
        }

    }
+1  A: 

If you call getTime() on a date object it will return a long with milliseconds since epoch (jan 1. 1970). Checking if a date is within the last year is then a simple matter of creating one date object with a date one year ago and doing comparison on the long values (someDate > aYearAgo). Alternatively you can use the after() method on a calendar object. To create a calendar/date object with a value one year ago you can use calObj.add(Calendar.YEAR, -1).

stian
+1  A: 

I believe something like this will get you the start of the calendar day so that time of day is not a factor.

GregorianCalendar calToday = new GregorianCalendar();
GregorianCalendar oneYearAgoTodayAtMidnight = new GregorianCalendar(calToday.get(Calendar.YEAR) - 1, calToday.get(Calendar.MONTH), calToday.get(Calendar.DATE));
steamer25
+1  A: 

This approach ignores leap-years (and other calendar-caused oddities), but is very straightforward:

public boolean isWithinAYear(Date inputDate) {
  Date d = new Date() // Get "now".
  long dLong = d.getTime();
  // You could multiply this next line out and use a single constant,
  // I didn't do that for clarity (and the compiler will optimize it 
  // out for us anyhow.)
  long oneYearAgo = dLong - (365 * 24 * 60 * 60 * 1000); 

  return inputDate.getTime() > oneYearAgo;
}

Your solution using GregorianCalendar is technically more correct.

Jared