'Best Way to check if a java.util.Date is older than 30 days compared to current moment in time?
Here's what I want to do:
Date currentDate = new Date();
Date eventStartDate = event.getStartDate();
How to check if eventStartDate is more than 30 days older than currentDate?
I'm using Java 8, Calendar isn't preferred.
Time zone is ZoneId.systemDefault().
Solution 1:[1]
You could try this:
Date currentDate = new Date();
Date eventStartDate = event.getStartDate();
long day30 = 30l * 24 * 60 * 60 * 1000;
boolean olderThan30 = currentDate.before(new Date((eventStartDate .getTime() + day30)));
It's disguisting, but it should do the job!
Solution 2:[2]
fun isOlderThan(interval: Int,previousTime : Long, currentTime: Long): Boolean {
val currentDate = Date(currentTime)
val previousDate = Date(previousTime)
val diffCalculate = abs(currentDate.time - previousDate.time)
val diffDays = diffCalculate / (24 * 60 * 60 * 1000)
return diffDays > interval
}
Use
val dateFormat = SimpleDateFormat("yyy-MM-dd")
val oldDate = dateFormat.parse("2022-02-01")
if(isOlderThan(7,oldDate.time,System.currentTimeMillis()){
Log.d("OLD CHECK","Old date is 7 days old")
}else{
Log.d("OLD CHECK","Old day is not 7 days old")
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
