Android Timestamp溢出问题:如何规避数值溢出及相关疑问
Great question—let’s unpack this clearly, since it’s a common gotcha with integer types in programming.
Fixing the Numeric Overflow (Without Switching to Seconds)
The root of your overflow warning is that when you calculate something like 30 * 24 * 60 * 60 * 1000, all those numbers are 32-bit int literals by default. Even though you’re assigning the result to a long, the multiplication happens first using int arithmetic, which maxes out at 2,147,483,647. Since 30 days in milliseconds is 2,592,000,000—which exceeds the int limit—the calculation overflows before it ever gets cast to long.
Here are three solid fixes:
- Promote one literal to long: Add an
Lsuffix to any of the numbers in the calculation to force the entire operation to use 64-bit arithmetic. For example:
This way, every subsequent multiplication uses long instead of int, avoiding overflow entirely.long monthlyMillis = 30L * 24 * 60 * 60 * 1000; - Use the
java.timeAPI (Java 8+): Let the standard library handle the safe calculation for you. It’s cleaner and less error-prone:
The library internally uses proper 64-bit calculations, so you don’t have to worry about manual arithmetic mistakes.import java.time.Duration; long monthlyMillis = Duration.ofDays(30).toMillis(); - Use a precomputed long constant: If the value doesn’t need to be dynamic, just define it directly as a long literal:
Simple and straightforward for fixed values.long MONTHLY_MILLIS = 2592000000L;
Why Epoch Milliseconds Fit in a Long
Your confusion here makes total sense—let’s clarify the ranges:
- A 32-bit signed
inthas a maximum value of2^31 - 1 = 2,147,483,647(about 2.1 billion). That’s why your 30-day calculation overflows when using ints. - A 64-bit signed
longhas a maximum value of2^63 - 1 = 9,223,372,036,854,775,807(about 9 quadrillion).
The number of milliseconds since the Unix epoch (January 1, 1970) as of 2024 is roughly 1.7 * 10^12—that’s 1.7 trillion, which is way smaller than the long’s maximum value. Even if you fast-forward to the year 3000, the epoch milliseconds will only be around 3.2 * 10^13—still nowhere near the 9-quadrillion limit of a long. So there’s no overflow here because we’re working within the 64-bit range from the start.
内容的提问来源于stack exchange,提问作者Sebastien FERRAND

