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).

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)

If you found this post useful, please feel free to share and give it a LIKE , so others can find it too! Also if you want more content like this please hit the FOLLOW button and don’t forget about the COMMENTS section below, Thanks 😊

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s