farhad.kargaran
farhad.kargaran

Reputation: 2373

Why adding value to a long variable makes it lower?

I am trying to add 30 days to System.long a = System.currentTimeMillis() + ((long)30 * 24 * 60 * 60 * 1000); but it is deceasing the value? Why? This is what i have tried

int days = 30;
long a = System.currentTimeMillis();
long b = a + (days * 24 * 60 * 60 * 1000);

According to the time I run the code, it was the result:

a = 1646737213282 , b = 1645034245986

Why b < a ?

Upvotes: 0

Views: 107

Answers (1)

Sambhav Khandelwal
Sambhav Khandelwal

Reputation: 3765

The issue is that the int range is being exceeded. The max int range is from

-2,147,483,648 (-231) to 2,147,483,647 (231-1)

When you multiply, it is stored as a int. But, that's not the limit. So, the solution will be to parse it to a long. You can check out my code below:

int days = 30;
long a = System.currentTimeMillis();
long b = a + ((long)days * 24 * 60 * 60 * 1000);
System.out.println("a = " + a + "       b = " + b);

But if you want to optimise the code, this code will be better:

long a = System.currentTimeMillis() + ((long)30 * 24 * 60 * 60 * 1000);
System.out.println("a = " + a);

It saves your 2 lines of code 🙂

But, I'd also prefer you to use a method

long addDays(int days){
    return System.currentTimeMillis() + ((long)days * 24 * 60 * 60 * 1000);
}

and then

int a = addDays(30);

Upvotes: 1

Related Questions