Java:基本数学错误?

aro*_*oth 3 java time date

我必须在这里做一些根本错误的事情.我的代码非常简单:

private static final long MILLIS_PER_YEAR = 1000 * 60 * 60 * 24 * 365;

//...

public long getAge() {
    long millis = System.currentTimeMillis() - this.getBirthdate().getTime();
    System.out.println("Computed age:  " + (millis / MILLIS_PER_YEAR) + ", birthdate=" + this.getBirthdate() + ", birthdateMillis=" 
            + this.getBirthdate().getTime() + ", now=" + new Date() + ", nowMillis=" + System.currentTimeMillis() 
            + ", elapsedMillis=" + millis);
    return millis / MILLIS_PER_YEAR;
}
Run Code Online (Sandbox Code Playgroud)

...但它会给出一些完全不正确的输出:

Computed age:  248, birthdate=2001-01-01 10:00:00.0, birthdateMillis=978307200000, now=Fri Aug 10 16:56:48 EST 2012, nowMillis=1344581808173, elapsedMillis=366274608173
Computed age:  184, birthdate=2004-01-01 10:00:00.0, birthdateMillis=1072915200000, now=Fri Aug 10 16:56:48 EST 2012, nowMillis=1344581808173, elapsedMillis=271666608173
Run Code Online (Sandbox Code Playgroud)

如果我手动(或使用谷歌)运行相同的计算,我会得到正确的结果(在合理的允许范围内,因为实际年份略多于365天).

同样的数学在这段代码中产生这种无意义的输出怎么样?

Joa*_*uer 13

价值MILLIS_PER_YEAR是错误的.这1471228928不是期望的31536000000.

查看值的计算:所有参与的值都是int值(数值,非小数常量int在Java中默认为-values).这意味着计算结果也是一个int值.但是所需的值大于int可以容纳的值,因此您将有溢出.

要确保对long值进行计算,只需将至少一个值设为long(通过附加L后缀):

private static final long MILLIS_PER_YEAR = 1000L * 60 * 60 * 24 * 365;
Run Code Online (Sandbox Code Playgroud)