Best way to get maximum Date value in java?

前端 未结 9 1239
眼角桃花
眼角桃花 2020-12-01 13:55

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

相关标签:
9条回答
  • 2020-12-01 14:10

    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);
            }
        }
    
        ...
    }
    
    0 讨论(0)
  • 2020-12-01 14:12

    have you considered adopting the use of Joda Time?

    It's slated to be included in java 7 as the basis for JSR-310

    The feature that may interest you is ZeroIsMaxDateTimeField which basically swaps zero fields for the maximum value for that field within the date-time.

    0 讨论(0)
  • 2020-12-01 14:16

    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.

    0 讨论(0)
提交回复
热议问题