user1742919
user1742919

Reputation: 401

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();
        }

Upvotes: 2

Views: 339

Answers (4)

cheshy
cheshy

Reputation: 179

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();
        }
    }
}

Upvotes: 2

Rajen Raiyarela
Rajen Raiyarela

Reputation: 5634

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.

Upvotes: 2

antonu17
antonu17

Reputation: 573

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);

Upvotes: 8

Ferrybig
Ferrybig

Reputation: 18834

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.

Upvotes: 3

Related Questions