[java] Compare two Timestamp in java

How can I compare if mytime is between fromtime and totime:

Timestamp fromtime;
Timestamp totime;

Timestamp mytime;

This question is related to java timestamp

The answer is


There are after and before methods for Timestamp which will do the trick


Just convert the timestamp in millisec representation. Use getTime() method.


Use the before and after methods: Javadoc

if (mytime.after(fromtime) && mytime.before(totime))

All these solutions don't work for me, although the right way of thinking.

The following works for me:

if(mytime.isAfter(fromtime) || mytime.isBefore(totime) 
    // mytime is between fromtime and totime

Before I tried I thought about your solution with && too


From : http://download.oracle.com/javase/6/docs/api/java/sql/Timestamp.html#compareTo(java.sql.Timestamp)

public int compareTo(Timestamp ts)

Compares this Timestamp object to the given Timestamp object. Parameters: ts - the Timestamp object to be compared to this Timestamp object Returns: the value 0 if the two Timestamp objects are equal; a value less than 0 if this Timestamp object is before the given argument; and a value greater than 0 if this Timestamp object is after the given argument. Since: 1.4


if (!mytime.before(fromtime) && !mytime.after(totime))

java.util.Date mytime = null;
if (mytime.after(now) && mytime.before(last_download_time) )

Worked for me


You can sort Timestamp as follows:

public int compare(Timestamp t1, Timestamp t2) {

    long l1 = t1.getTime();
    long l2 = t2.getTime();
    if (l2 > l1)
    return 1;
    else if (l1 > l2)
    return -1;
    else
    return 0;
}

if(mytime.after(fromtime) && mytime.before(totime))
  //mytime is in between