Best way to get maximum Date value in java?

Try

new Date(Long.MAX_VALUE)

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


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

    ...
}

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


Here is what I do:

public static final TimeZone UTC;

// 0001.01.01 12:00:00 AM +0000
public static final Date BEGINNING_OF_TIME;

// new Date(Long.MAX_VALUE) in UTC time zone
public static final Date END_OF_TIME;

static
{
    UTC = TimeZone.getTimeZone("UTC");
    final Calendar c = new GregorianCalendar(UTC);
    c.set(1, 0, 1, 0, 0, 0);
    c.set(Calendar.MILLISECOND, 0);
    BEGINNING_OF_TIME = c.getTime();
    c.setTime(new Date(Long.MAX_VALUE));
    END_OF_TIME = c.getTime();
}

Note that if the TimeZone is NOT UTC you will get offsets from the "end of time", which won't be maximal values. These are especially useful for inserting into Database fields and not having to have NULL dates.