简体   繁体   中英

Getting past date results in future date

I have code:

java.util.Date purgeBackDate = new java.util.Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 390));
System.out.println(purgeBackDate);

I was expecting to print the date for 390 days ago, but instead, it prints a future date: Fri Aug 21 05:57:11 EDT 2015

I also tried to replace System.currentTimeMillis() with new java.util.Date().getTime() , and I am getting the same result. I am very confused because minus from the millisec used to work before.

I am using JDK 1.6 and 1.7 (both give this result): Test Code

Your multiplication is all with int s and is overflowing to a negative number, which, when subtracted, yields a date in the future.

Cast the 1000 to long or use a long literal 1000L to use a much wider valid number range and to get the correct number to subtract, and you'll get a date in the past.

try Calendar instead:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -390);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM