Kiarash Kiarash - 3 years ago 154
Java Question

Java Date object shows time in the future

I'm making a new date object some time before current time. If I have it to show 1 day before today, it works fine. but if I want to show 30 days ago, it goes to future (?)

Date date = new Date();
long sometime = 24 * 60 * 60 * 1000; //a day
System.out.println(date.getTime() );
Date sometimeago = new Date(date.getTime() - sometime);
System.out.println(sometimeago );
sometime = 30* 24 * 60 * 60 * 1000; //a month
sometimeago = new Date(date.getTime() - sometime);
System.out.println(sometimeago );


Output:

1408160853776
Thu Aug 14 20:47:33 PDT 2014
Thu Sep 04 13:50:21 PDT 2014


What's limiting here? Reaching Long limit?

Answer Source

integer overflow in int literals,

in your case int literals gets evaluted before and that results in negative result and than gets assigned to long

sometime = 30* 24 * 60 * 60 * 1000; //a month 

this results in -1702967296

convert it to

sometime = 30* 24 * 60 * 60 * 1000L; //a month 

note: L to make it long literal and then multiply

Better to use Calendar class for Date manipulation


Also See

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download