Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get maximum Date value in java?

Tags:

java

datetime

I'm writing a bit of logic that requires treating null dates as meaning forever in the future (the date in question is an expiration date, which may or may not exist). Instead of putting in special cases for a null date throughout the code, I want to just convert null into the maximum possible Date. I don't see any obvious ways to get such a value without hard coding it. What's the best way to get the maximum value of whatever Date implementation is being used?

like image 252
jthg Avatar asked Nov 16 '09 18:11

jthg


People also ask

How do you find the maximum date?

Max function to find latest date If you want to find out the latest dates in the range, you can enter the formula =MAX(A1:D7), and press the Enter key.


3 Answers

Try

new Date(Long.MAX_VALUE) 

which should give you the longest possible date value in Java.

like image 156
cjstehno Avatar answered Oct 12 '22 07:10

cjstehno


Encapsulate the functionality you want in your own class, using Long.MAX_VALUE will most likely cause you problems.

class ExpirationDate {     Date expires;      boolean hasExpiration() {         return expires == null;     }      Date getExpirationDate() {         return expires;     }       boolean hasExpired(Date date) {         if (expires == null) {             return true;         } else {             return date.before(expires);         }     }      ... } 
like image 29
Tom Avatar answered Oct 12 '22 07:10

Tom


+1 to the Long.MAX_VALUE suggestions. It seems that this would help you if you sort stuff by your date field.

However, instead of constructing a date from some the large constant value where ever you need the date, use a globally visible singleton to hold a Date instance that represents your special value:

class DateUtil
{
  public static final Date NO_EXPIRE = new Date( Long.MAX_VALUE );
}

Then you can use simple identity comparison (mydate == DateUtils.NO_EXPIRE) to test if a particular date is of your special case instead of obj.equals(); (ie. mydate.equals ( DateUtils.NO_EXPIRE ); )

like image 40
Trevor Harrison Avatar answered Oct 12 '22 07:10

Trevor Harrison