1

I am trying to compute a return date in milliseconds based on outgoing date in milliseconds and days in destination. I chose to do that by adding daysIn * 86400000 to outgoing date, where 86400000 represents a day in milliseconds.

long newReturn = newOut + (daysIn * 86400000);

The second part of this expression is seemingly not working. If I set daysIn to 30, daysIn * 86400000 is apparently -1702967296. I expect 2592000000 so this obviously causes my newReturn value to be wrong.
If the value is small, e.g. 2, it works fine so I don't understand this problem.

These are the types of variables:

long newReturn; 
long newOut; 
int daysIn;

I thought maybe there would be an issue with type but long can handle large numbers and it all works if daysIn is 24 or less. Any ideas on what can cause the error or how to fix it? Anything will be appreciated.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Naty
  • 25
  • 4
  • Have you tried `86400000L`? – EpicPandaForce Aug 07 '18 at 22:41
  • Wow that fixed it! Thanks! So was the problem in 86400000 being marked as integer or what did adding L do? – Naty Aug 07 '18 at 23:08
  • `daysIn` was an `int`, `86400000` was an `int`, so `daysIn * 86400000` was an int (kind of) and it totally overflowed. This happened to me once before and we ended up with a certificate expiration date after `-6 days` and I was like d'oh -- so yes, adding `L` at the end makes it a `long` and so it works – EpicPandaForce Aug 07 '18 at 23:16

1 Answers1

0

The questions marked as duplicate were about "how to check if my operation will cause overflow", which is not helpful in resolving said overflow. I reopened this question as such.


daysIn is an int, 86400000 is an int, so daysIn * 86400000 was an int (kind of) and it overflows.

The solution is to either make daysIn a long, or specify 86400000 as a long: namely 86400000L.

long newReturn = newOut + (daysIn * 86400000L); // should work as intended
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428