Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the difference between 2 dates is more than 20 minutes

Tags:

java

date

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?

like image 299
Akshay Avatar asked Aug 16 '11 14:08

Akshay


People also ask

How do you find the difference between two dates and minutes?

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.

How do you compare long dates?

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.

How do you compare two dates without the time portion?

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.

How do you find the difference between two dates?

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.


2 Answers

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) {     ... } 
like image 65
aioobe Avatar answered Sep 18 '22 08:09

aioobe


Using Joda Time:

boolean result = Minutes.minutesBetween(new DateTime(previous), new DateTime())                         .isGreaterThan(Minutes.minutes(20)); 
like image 24
dogbane Avatar answered Sep 20 '22 08:09

dogbane