0

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 ?

Sambhav Khandelwal
  • 3,585
  • 2
  • 7
  • 38
farhad.kargaran
  • 2,233
  • 1
  • 24
  • 30
  • 2
    try to print `(days * 24 * 60 * 60 * 1000)` - that is an `int` operation since all operands are `int` - it will overflow and become negative (`-1702967296`) || solution: declare `days` as `long` or use cast `((long) day * 24 * ...)` {or just add an L to 24 `(day * 24L * ...)` not so easy to spot}) – user16320675 Mar 08 '22 at 11:08
  • 1
    The `(days * 24 * 60 * 60 * 1000)` computation is done using 32 bit (`int`) arithmetic, and it probably overflows. Change it to `((long) days * 24 * 60 * 60 * 1000)` or declare `days` as `long`. – Stephen C Mar 08 '22 at 11:09
  • 2
    change `days` to `long`, in order to perform long multiplications. – Eran Mar 08 '22 at 11:09
  • as @user16320675 and others mentioned, days should be long too :-\ It could be an exam question :)))) – farhad.kargaran Mar 08 '22 at 11:16

1 Answers1

1

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);
Sambhav Khandelwal
  • 3,585
  • 2
  • 7
  • 38