Fix int overflow in DurationFormatUtils.formatPeriod#1720
Merged
Conversation
garydgregory
requested changes
Jun 20, 2026
garydgregory
left a comment
Member
There was a problem hiding this comment.
Hello @alhudz
Thank you for the PR.
Would you please add a tests that:
- asserts that the right formatting happens for inputs around and at
Long.MAX_VALUE, for example the duration starting atLong.MAX_VALUE -1and ending atLong.MAX_VALUE. - Same for
Long.MIN_VALUE - Same for
Integer.MIN_VALUE
This should hopefully show that we can correctly handle the full range of long millisecond values for the input to this method.
TY!
Contributor
Author
|
Added
Each one asserts |
garydgregory
added a commit
that referenced
this pull request
Jun 20, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Thanks for your contribution to Apache Commons! Your help is appreciated!
Before you push a pull request, review this list:
mvn; that'smvnon the command line by itself.Repro:
DurationFormatUtils.formatPeriod(0, 2175984000000L, "s", true, gmt)for a ~69 year span (gmtisTimeZone.getTimeZone("GMT")).Expected:
2175984000, the value the siblingformatDuration(2175984000000L, "s")returns for the same span.Actual:
-2118983296.Cause:
formatPeriodkeeps its day/hour/minute/second estimates inint. When the format omits a higher field, that field is funnelled into the next lower one (hours += 24 * days,minutes += 60 * hours,seconds += 60 * minutes) inintarithmetic before the values widen to thelongparameters offormat. Past a few decades the second (or millisecond) count exceedsInteger.MAX_VALUEand the multiply wraps negative.Fix: declare the six estimate locals as
longso the reduction runs inlong, the same wayformatDurationalready reduces the span.millisecondswas alreadylong; normal-size durations produce identical output.