File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Adding to Date produces unexpected result Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Adding to Date produces unexpected result" Watch "Adding to Date produces unexpected result" New topic
Author

Adding to Date produces unexpected result

Ron Meyer
Greenhorn

Joined: Jun 26, 2012
Posts: 7

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

Joined: Jan 10, 2002
Posts: 61209
    
  66

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?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3546
    
  15
You might also want to take a look at the Calendar class that has an add method specifically for this purpose.


Joanne
Ron Meyer
Greenhorn

Joined: Jun 26, 2012
Posts: 7

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));
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Adding to Date produces unexpected result