Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java calculating past date from today is going into the future

Tags:

java

datetime

I'm having an issue in Java calculating the current date minus a certain amount of days.

I have:

Date pastDate = new Date(new Date().getTime() - (1000 * 60 * 60 * 24 * 25));

This is returning Tue Feb 16 09:04:18 EST 2016 when it should actually return Tue Dec 28 16:06:11 EST 2015 (25 days into the past).

What's very strange is that for any number under 25 days works completely fine:

Date pastDate = new Date(new Date().getTime() - (1000 * 60 * 60 * 24 * 24));

As in 24 days into the past returns a predictable Tue Dec 29 16:06:11 EST 2015.

Any help would be appreciated.

like image 734
Abushawish Avatar asked Jan 22 '16 21:01

Abushawish


People also ask

How do I set the past date in Java?

time. LocalDate. Use LocalDate 's plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.

How do you check if a date is in the past Java?

1. Java 8 isBefore() First minus the current date and then uses isBefore() to check if a date is a certain period older than the current date.

How do you calculate elapsed days in Java?

To get the elapsed time of an operation in days in Java, we use the System. currentTimeMillis() method.


1 Answers

With 24 days, the product remains just below the maximum possible int value, Integer.MAX_VALUE, which is 2,147,483,647. The 24 days product is 2,073,600,000. The 25 days product is 2,160,000,000. The result is overflow and a negative number, resulting in a date in the future.

For such values, use a long literal for the first value (or cast it to a long) to avoid the overflow that comes with exceeding Integer.MAX_VALUE. Note the L appended to 1000L:

(1000L * 60 * 60 * 24 * 25)

This works fine because the desired constructor for Date takes a long.

Date arithmetic is handled more cleanly by using Calendars, where you can explicitly add a negative number of days.

Also, with Java 8+, you can use Instant and its minus method to subtract the time.

Instant.now().minus(24, ChronoUnit.DAYS);
like image 145
rgettman Avatar answered Oct 21 '22 22:10

rgettman