Java Computation Bug
Let’s say we have the following piece of code:
…
public long plusDays(int days) {
long timestamp = Calendar.getInstance().getTimeInMillis();
return timestamp + (1000 * 60 * 60 * 24 * days)
}
…
This method can be used to add a specific number of days to the current timestamp and is incorrect :) .
Let’s assume the current timestamp is 1522734845054 (April 3, 2018 5:54:05.054 AM). If we call plusDays(10) it will correctly return something like 1523598845054 (April 13, 2018 5:54:05.054 AM). But if we call plusDays(30) it will return 1521031877758 (March 14, 2018 12:51:17.758 PM) obviously incorrect.
Why is this happening?
Well it’s actually very simple, the formula between brackets 1000 * 60 * 60 * 24 * days is actually an integer formula and in case the day value is big enough, this formula will be greater than the MAX_INT value and will be evaluated to the Integer.MinValue(-2147483648).
Get Toth Arpad’s stories in your inbox
Join Medium for free to get updates from this writer.
So in order for this code to work, we must make sure that the formula between brackets is evaluated as a long formula. We do this by casting any of it’s members to long. The correct code should be something like this :
…
public long addDays(long timestamp, int days) {
long timestamp = calendar.getTimeInMillis();
return timestamp + (1000 * 60 * 60 * 24 * (long)days)
}
…Thanks for reading — if you enjoyed it, please do mash the 👏button and share it with your friends. Thanks 😊








