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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Adding to Date produces unexpected result" Watch "Adding to Date produces unexpected result" New topic

Adding to Date produces unexpected result

Ron Meyer

Joined: Jun 26, 2012
Posts: 7


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

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

Output is:

Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 60800

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

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

Ron Meyer

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));
It is sorta covered in the JavaRanch Style Guide.
subject: Adding to Date produces unexpected result
Similar Threads
Working with Date and Time
Calendar() / Date() bug ???
java dates