Best way to get maximum Date value in java?

前端 未结 9 1238
眼角桃花
眼角桃花 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 13:59

    Try

    new Date(Long.MAX_VALUE)
    

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

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

    I like Instant.MAX because it is more likely to be supported in the future than Long.MAX_VALUE.

    Note that as of today, though, Instant.MAX.toEpochMilli() throws an overflow error.

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

    One problem I see is that for sorting on expiration date, using a null isn't easily sortable. So replacing with an actual value (even if it's an arbitrary sentry value well into the future) may be needed.

    I suppose another way of treating "no expiration" is simply to say something expires 100 years in the future... Unless your database is dealing with long-term contracts!

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

    From Java SE 8 you could use:

    LocalDate.MAX
    
    0 讨论(0)
  • 2020-12-01 14:07

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

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

    Perhaps one option is to use the maximal system date. You can get it by using:

    System.out.println(new Date(Long.MAX_VALUE).toString())
    //Output:
    //Sun Aug 17 12:42:55 IST 292278994
    
    0 讨论(0)
提交回复
热议问题