Karthikeyan Karthik
Karthikeyan Karthik

Reputation: 114

How to compare two date and time in android

I have one problem is there. How to compare 2 date and time

enter code here
if(fromdate<=nowdt.now() && todate>= nowdt.now()){
////

}

Upvotes: 0

Views: 15767

Answers (6)

Karthikeyan Karthik
Karthikeyan Karthik

Reputation: 114

use this answer

if((options.FromDate.before(now_Date)||options.FromDate.equals(now_Date)) && (options.ToDate.after(now_Date)|| options.ToDt.equals(now_Date)) ){

do some processs........
}

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533930

You can write

long nowTime = System.currentTimeMillis();
if(fromdate.getTime() <= nowTime && nowTime <= todate.getTime()) {

or you can write

Date nowDate = new Date();
if(fromdate.compareTo(nowDate) * nowDate.compareTo(todate) >= 0) {

or

if(!fromdate.after(nowDate) && !todate.before(nowDate))

Upvotes: 0

Gridtestmail
Gridtestmail

Reputation: 1479

Try this one out to find time difference

  Calendar Day = Calendar.getInstance();
  Day.set(Calendar.DAY_OF_MONTH,25);
  Day.set(Calendar.MONTH,7); 
  Day.set(Calendar.YEAR, 1985);

  Calendar today = Calendar.getInstance();

  long diff = today.getTimeInMillis() - Day.getTimeInMillis();

Upvotes: 0

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

- Use Joda Time library to do this....

Eg:

Date ds = new Date();
DateTime d = new DateTime(ds);

DateTime e = new DateTime(2012,12,07, 0, 0);
System.out.println(d.isEqual(e));


System.out.println(d.toDateMidnight().isEqual(e.toDateMidnight()));

///////////////////////////// OR

System.out.println(d.withTimeAtStartOfDay().isEqual(e.withTimeAtStartOfDay()));

Upvotes: 0

MysticMagicϡ
MysticMagicϡ

Reputation: 28823

A function to compare two date and time:

public static int compareTwoDates(Date date1, Date date2) {
        if (date1 != null && date2 != null) {
            int retVal = date1.compareTo(date2);

            if (retVal > 0)
                return 1; // date1 is greatet than date2
            else if (retVal == 0) // both dates r equal
                return 0;

        }
        return -1; // date1 is less than date2
    }

You can use it where you want to. Result will be > 0 if date1 > date2, = 0 if date1 = date2, < 0 if date1 < date2. Hope it helps.

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

The java.util.Date object contains methods .before(), .after and .equals() for comparing dates.

if((fromdate.before(nowDt) || fromDate.equals(nowDt)) 
    && ((todate.after(nowDt) || toDate.equals(nowDt))
////

}

Upvotes: 11

Related Questions