You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Timestamp溢出问题:如何规避数值溢出及相关疑问

How to Avoid Numeric Overflow When Calculating Monthly Milliseconds (And Why Epoch Milliseconds Fit in a Long)

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 L suffix to any of the numbers in the calculation to force the entire operation to use 64-bit arithmetic. For example:
    long monthlyMillis = 30L * 24 * 60 * 60 * 1000;
    
    This way, every subsequent multiplication uses long instead of int, avoiding overflow entirely.
  • Use the java.time API (Java 8+): Let the standard library handle the safe calculation for you. It’s cleaner and less error-prone:
    import java.time.Duration;
    
    long monthlyMillis = Duration.ofDays(30).toMillis();
    
    The library internally uses proper 64-bit calculations, so you don’t have to worry about manual arithmetic mistakes.
  • Use a precomputed long constant: If the value doesn’t need to be dynamic, just define it directly as a long literal:
    long MONTHLY_MILLIS = 2592000000L;
    
    Simple and straightforward for fixed values.

Why Epoch Milliseconds Fit in a Long

Your confusion here makes total sense—let’s clarify the ranges:

  • A 32-bit signed int has a maximum value of 2^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 long has a maximum value of 2^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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:06:08