Why subtraction of more than 30 days resulting wrong answer

If I try to subtract 1 to 29 days the return date is correct but if I try to subtract more than 30 days the return date is wrong. Can anybody explain where I'm going wrong?

public class MapTesting {
    public static void main(String[] args) {
        Date dNow = new Date( );
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-dd-MM");

        try {
            Date date = ft.parse("2011-01-10");
            Date su=new Date(date.getTime()-30*24*3600*1000);
            System.out.println(su);
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

Answers


You have overflow in int constant: 30*24*3600*1000.

Try to cast ints to long: Date su=new Date(date.getTime() - 30 * 24 * 3600 * 1000L);


This is because of Integer underflow/overflow.

When a integer goes too high, it will go from positive to negative.

Example of this:

System.out.println(24*24*3600*1000); // = 2073600000
System.out.println(25*24*3600*1000); // = -2134967296

When the we celebrated the new millennium ,people were also scared for this when their 99 went overflowing to 00.

To fix this problem, you could cast 1 of the numbers to a Long by 30l*24*3600*1000.


As @antonu17 mentioned, you are having overflow error.

If you want date before or after than you can directly do that calculations on calendar object.

Calendar cal = Calendar.getInstance();
cal.add (Calendar.DAY_OF_MONTH, (-/+)30); //you can add - sign to 30 if you want current date -30 days.

Then get date from this calendar object.


The Date constructor is expecting a long value. The code works if you specify long values:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MapTesting {
    public static void main(String[] args) {
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-dd-MM");

        try {
            Date date = ft.parse("2011-01-10");
            Date su = new Date(date.getTime() - 30L * 24L * 3600L * 1000L);
            System.out.println(su);
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Need Your Help

File is used by another process. How to know which process?

.net windows file-access

I keep getting that exception in my program. How do I know which process locked it, either by program code or by doing something with windows?

Submitting beta iPhone app to store

ios xcode app-store

My company is working on a dynamic mobile app that updates the look and appearance based on webcalls and we would like to be able to test that it would be able to get into the store okay. For the t...