I have a datetime in a variable previous
. Now i want to check if the previous datetime is more than twenty minutes before the current time.
Date previous = myobj.getPreviousDate(); Date now = new Date(); //check if previous was before 20 minutes from now ie now-previous >=20
How can we do it?
Math. abs is used to be able to use the absolute difference (so new Date('2011/10/09 00:00') - new Date('2011/10/09 12:00') gives the same result). Dividing the result by 1000 gives you the number of seconds. Dividing that by 60 gives you the number of minutes.
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
If you want to compare only the month, day and year of two dates, following code works for me: SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); sdf. format(date1). equals(sdf.
Use the DATEDIF function when you want to calculate the difference between two dates. First put a start date in a cell, and an end date in another. Then type a formula like one of the following.
Use
if (now.getTime() - previous.getTime() >= 20*60*1000) { ... }
Or, more verbose, but perhaps slightly easier to read:
import static java.util.concurrent.TimeUnit.*; ... long MAX_DURATION = MILLISECONDS.convert(20, MINUTES); long duration = now.getTime() - previous.getTime(); if (duration >= MAX_DURATION) { ... }
Using Joda Time:
boolean result = Minutes.minutesBetween(new DateTime(previous), new DateTime()) .isGreaterThan(Minutes.minutes(20));
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