Compare two Timestamp in java

JavaTimestamp

Java Problem Overview


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

Timestamp fromtime;
Timestamp totime;

Timestamp mytime;

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

Use the before and after methods: Javadoc

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

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

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

Worked for me

Solution 7 - Java

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;
}

Solution 8 - Java

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

Solution 9 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser620130View Question on Stackoverflow
Solution 1 - JavalegendofawesomenessView Answer on Stackoverflow
Solution 2 - JavaJean LogeartView Answer on Stackoverflow
Solution 3 - JavaNickLHView Answer on Stackoverflow
Solution 4 - JavaMaurice PerryView Answer on Stackoverflow
Solution 5 - JavaVladimirView Answer on Stackoverflow
Solution 6 - JavaNITINView Answer on Stackoverflow
Solution 7 - JavaborchvmView Answer on Stackoverflow
Solution 8 - JavaGiulia JJ MerliniView Answer on Stackoverflow
Solution 9 - JavaShubham MehtaView Answer on Stackoverflow