-2

I have this date and I want to forward it ahead in time, adding a few weeks to it.

This is how I do it

    int weeks = 4;

newDate.set(Calendar.HOUR_OF_DAY, hoursAndMinutes.get(Calendar.HOUR_OF_DAY));
newDate.set(Calendar.MINUTE, hoursAndMinutes.get(Calendar.MINUTE));
newDate.set(Calendar.SECOND, 0);
newDate.set(Calendar.MILLISECOND, Utils.returnRandomNumberBetween(1, 999));
dateFormat.format(newDate.getTime());

dateInMiliseconds = newDate.getTimeInMillis() + weeks * 604800000; // 604800000 is a week's worth of miliseconds

Now, instead of moving the date like 4 weeks ahead, it moves it back to the same week day but in May?

EDIT: To the guys that pointed out my question is a possible duplicate - it would have been a possible duplicate if I knew the problem was in casting, which I didnt know.

Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180
  • 3
    Is the product higher than 2^31? – chrylis -cautiouslyoptimistic- Jun 12 '14 at 13:29
  • FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. Much of the java.time functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 09 '18 at 00:46

2 Answers2

2

Integer overflow. weeks * 604800000 is computed as 32-bit signed int and it overflows. Specifically, its bit #31 (the sign bit) is set, making it negative.

Promote either operand to long to compute as 64-bit signed long integers, e.g.

dateInMiliseconds = newDate.getTimeInMillis() + weeks * 604800000L;
laalto
  • 150,114
  • 66
  • 286
  • 303
1

Integer overflow from weeks * 604,800,000

Max integer value is ~2,147,000,000 you multiply 4 with 604,800,000 ~= 2,400,000,000

Kevin L
  • 1,066
  • 3
  • 12
  • 21