This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adding to Date produces unexpected result

 
Ron Meyer
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hello,

can somebody please explain me why adding weeks to a Date doesn't work properly?
Thanks

Imagine the following code, which adds 3 and 4 weeks:




Output is:



Thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64629
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Problem #1: You're using a deprecated constructor. Avoid this.

Real problem: date values are longs. You're doing int arithmetic. How do you change that?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might also want to take a look at the Calendar class that has an add method specifically for this purpose.
 
Ron Meyer
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks for the reply, so it is an overflow.
Fixed it by using a long in the multiplication.
A bit ugly though, but better then a (long) cast in the line.


Yeah i know the constructor is deprecated, unfortunately this should also be used for GWT and there is *only* Date available.
And probably it was a bad idea in JDK to make Date mutable as well.

Is there any way a Exception or warning could be issued when variables over/underflow?


Fixed version
Date start = new Date(2013-1900, 0, 1);
long week = 7*24*60*60*1000;
System.out.println("date ( + 3weeks)" + new Date(start.getTime() + 3 * week));
System.out.println("date ( + 4weeks)" + new Date(start.getTime() + 4 * week));
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic