Java: basic math errors?
I have to do something fundamentally wrong here My code is very simple:
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; }
... but it will give some completely incorrect output:
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,elapsedMillis=271666608173
If I run the same calculation manually (or by using Google), I get correct result (within a reasonable allowance, because the actual year is slightly more than 365 days)
How about the same math producing this meaningless output in this code?
Solution
MILLIS_ PER_ The value of year is incorrect It is 1471228928 instead of the required 31536 million
Check the value calculation: all participating values are int values (numeric values, non decimal constants are int values by default in Java) This means that the calculation result is also an int value However, the required value is greater than int can hold, so you will overflow
To ensure that long values are calculated, simply set at least one value to long (by appending an L suffix):
private static final long MILLIS_PER_YEAR = 1000L * 60 * 60 * 24 * 365;