Lisa
Lisa

Reputation:

how to find out whether or not a date is 1 year before today's date in java

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
        }

    }

Upvotes: 2

Views: 9452

Answers (5)

Basil Bourque
Basil Bourque

Reputation: 338211

The java.util.Date & .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package bundled with Java 8 (and inspired by Joda-Time).

Joda-Time

If you are certain you want date only without time or time zone, use the LocalDate class (found in both Joda-Time and java.time).

Note the use of a time zone when asking for the current date. The date varies depending on where you are at on earth at the moment. If you fail to specify a date, the JVM’s default time zone will be used. Generally better to specify.

Here is some example code using Joda-Time 2.3.

String input = "01/19/2005";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
LocalDate localDate = LocalDate.parse( input, formatter );
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
LocalDate now = LocalDate.now( timeZone );
LocalDate yearAgo = now.minusYears( 1 );
boolean withinYearAgo = ( ( localDate.isAfter( yearAgo ) ) & ( localDate.isBefore( now ) ) );

Dump to console…

System.out.println( "input: " + input );
System.out.println( "localDate: " + localDate );
System.out.println( "now: " + now );
System.out.println( "yearAgo: " + yearAgo );
System.out.println( "withinYearAgo: " + withinYearAgo );

When run…

input: 01/19/2005
localDate: 2005-01-19
now: 2014-04-10
yearAgo: 2013-04-10
withinYearAgo: false

You might want to add a test for "or is equal to" depending on your definition of "within last year".

Upvotes: 2

John Hogan
John Hogan

Reputation: 1036

This woks perfectly.

public class X {

 public static Date date ;

public static Date date1 ;


/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

   Calendar cal = Calendar.getInstance();
 cal.add(Calendar.YEAR, 0); 

    boolean time;

 date = cal.getTime();
    System.out.println(date);
 time =  withinYear(date);

   System.out.println(time);

}


private static boolean result;
public static  boolean withinYear(Date inputDate)
{
   Calendar todaysDateMinus1Year = Calendar.getInstance();
todaysDateMinus1Year.add(Calendar.YEAR, -1);


date1 = todaysDateMinus1Year.getTime();

if (inputDate.before(date1))
            result= true;
            return result;

}

Upvotes: 0

Jared
Jared

Reputation: 26129

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.

Upvotes: 1

steamer25
steamer25

Reputation: 9538

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));

Upvotes: 1

stian
stian

Reputation: 2894

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).

Upvotes: 1

Related Questions