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.
time. LocalDate. Use LocalDate 's plusDays() and minusDays() method to get the next day and previous day, by adding and subtracting 1 from today.
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.
To get the elapsed time of an operation in days in Java, we use the System. currentTimeMillis() method.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With