My photo
Auckland, New Zealand
Smurf sized geeky person with a penchant for IT, gaming, music and books. Half of industrial duo 'the craze jones'. Loves data, learning new things, teaching new things and being enthusiastic.

Thursday, 7 June 2012

Java Date Comparisons

I've just started to use Java, having never coded with it before, and today ran into a bit of trouble with date comparisons.  The obvious option that I wanted to use had been deprecated so I needed to find an alternate.

Whilst Google and StackOverflow are normally my very best friends when it comes to this sort of issue, today they were only a little helpful, pointing me in roughly the right direction but not actually hitting the target.

What I needed to do was add 6 years to a variable date and then compare that to today's date.  Sounds easy enough, and in Java version 6 it was, but now things have changed.  

I found a useful class called Calendar, however, all the online blogs, tutorials and user comments only showed me how to add years to today's date, which is easy as pie.  What none of them told me was how to add 6 years to another date.   It's probably really obvious for most folks out there, but given the number of questions I found by people asking how to do this but only being told how to update today's date, I thought it best to post the solution.

So, first step, you need to make sure you've got the various java classes that you need, including Calendar, I do this by adding the following:

                import java.util.*;   //get everything you may possibly need...

Next step is optional, I do this just to make it easier to read the code further down the line and to make life easier for any devs who may read my code in years to come.

               //create a path to the objects we need to check
         YourDomainName dn =   ((YourDomainName)ctx.getViewInstance().getViewTree().getRoot().getDomain());

Now we need to create our date object using the Calendar class:

        //create a date that we can use for comparison checks
       Calendar dateToTestPlusSix = Calendar.getInstance();

       //set dateToTestPlusSix as the date entered by user on form       
       dateToTestPlusSix .setTime(dn.getFormEnteredDate()); 
       //add 6yrs to dateToTestPlusSix
       dateToTestPlusSix .add(Calendar.YEAR,6);    
Now we have a date object we can compare against, we need to use either the 'before' or 'after' actions associated with the date class:

       //check date + 6 years is AFTER today as it must be less than six years old
       if (dn.getFormEnteredDate().after(dateToTestPlusSix.getTime()))  
          DO STUFF;
          DO OTHER STUFF;

Clear as mud?  Let me know if this solution works for you or if you have alternate methods of comparing dates in Java v.7

No comments: