I am trying to remove the entries in my database that have Date (java.util.Date) older than 10 days of the current date. Is there any way to compare just the "day" value inside the Date. Not just comparing which Date value is greater, but actually making sure there is X day in between the two Date values.
Asked
Active
Viewed 4,013 times
2
-
what kind of database you are using? – Bharath Jun 25 '14 at 16:22
-
1Date is old news. I would use Calendar API, or the new datetime api in java 8 – Cruncher Jun 25 '14 at 16:22
-
no using Joda time library here – mirage1s7 Jun 25 '14 at 16:24
-
What about java.time from Java 8? Is that out, too? See http://stackoverflow.com/a/22512338/636009 or http://stackoverflow.com/questions/3526485/how-do-you-subtract-dates-in-java or the question @AlexandruCimpanu linked to. – David Conrad Jun 25 '14 at 16:33
-
Searching for "Joda" and "plusDays" or "minusDays" will provide many answers. – Basil Bourque Jun 25 '14 at 16:51
2 Answers
6
Say you have your two Date values as time1
and time2
.
int daysApart = (int)((time2.getTime() - time1.getTime()) / (1000*60*60*24l));
if (abs(daysApart) >= 10)
System.out.println("10+ days apart.");
else
System.out.println("Less than 10 days apart.");

krodmannix
- 845
- 10
- 30
-
I would presume that if time1 was at 9pm, and time 2 was 10 days later at 9am it would still want to match – Cruncher Jun 25 '14 at 16:27
-
-
So? Your integer division will make that 9 days, not 10. Since time2 is less than a full 10 days after time1. – Cruncher Jun 25 '14 at 17:04
-
(time2.getTime()/(1000*60*60*24l) - time1.getTime()/(1000*60*60*24l)) this works – mirage1s7 Jun 25 '14 at 17:38
-
Exactly. Less than 10 full days is not we the question asked for, but for 10 days apart @Cruncher – krodmannix Jun 25 '14 at 18:36
0
Just create a new Date object for current date + 10 days and compare to that.
i.e.
new Date(System.currentTimeMillis()+10L*24*60*60*1000);
As the comments say though the Date objects are pretty much obsolete now, you should look to using one of the more current time approaches.

Tim B
- 40,716
- 16
- 83
- 128