17

I tried to create a max Duration in Java 8 by using Duration.ofMillis(Long.MAX_VALUE) but got a long overflow. How would I programmatically get the equivalent of a Duration.MAX_VALUE if it existed?

Edit: The long overflow was likely caused by an attempt to add to the value instead of during construction. Apologies for not having reproducible code.

Novaterata
  • 4,356
  • 3
  • 29
  • 51

3 Answers3

14

Simple:

Duration maxDur = ChronoUnit.FOREVER.getDuration();
Nick J. R. T.
  • 370
  • 3
  • 8
  • 1
    Wow, no idea this existed, definitely what I was looking for way back when – Novaterata Mar 05 '20 at 16:23
  • which is defined as `FOREVER("Forever", Duration.ofSeconds(Long.MAX_VALUE, 999_999_999))` and documented as "... The estimated duration of this unit is artificially defined as the **largest duration supported by Duration**." – user85421 Mar 05 '20 at 16:25
9

It looks like Duration is stored in seconds (up to Long.MAX_VALUE) and nanoseconds (up to 999,999,999). Then the biggest duration possible is:

Duration d = Duration.ofSeconds(Long.MAX_VALUE, 999_999_999);

When I print it (System.out.print(d)) I get the following:

PT2562047788015215H30M7.999999999S

which means: 2562047788015215 hours, 30 minutes, and 7.999999999 seconds.

Alexey
  • 2,542
  • 4
  • 31
  • 53
8

According to the Javadoc:

The duration uses nanosecond resolution with a maximum value of the seconds that can be held in a long.

The range of a duration requires the storage of a number larger than a long. To achieve this, the class stores a long representing seconds and an int representing nanosecond-of-second, which will always be between 0 and 999,999,999. The model is of a directed duration, meaning that the duration may be negative.

Community
  • 1
  • 1
jhamon
  • 3,603
  • 4
  • 26
  • 37
  • 2
    So why would Long.MAX_VALUE cause an overflow? What is the maximum value allowed for the Seconds portion? – Novaterata Jul 06 '16 at 15:39
  • 5
    well, I just tried this piece of code: `Duration test = Duration.ofMillis(Long.MAX_VALUE);`and I don't get an overflow. Could you show the code that throws the exception? – jhamon Jul 06 '16 at 15:48
  • I no longer have it sorry. You know, it must have been caused later when something was added to it. – Novaterata Jul 06 '16 at 17:12