2011-10-27 177 views
31

2個時間戳我怎樣才能比較,如果mytimefromtimetotime之間:比較在Java

Timestamp fromtime; 
Timestamp totime; 

Timestamp mytime; 

回答

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

考慮莫里斯·佩裏的反應,如果要包括'fromTime'和'toTime' –

12

使用beforeafter方法:Javadoc

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

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

public int compareTo(Timestamp ts) 

比較此Timestamp對象與給定Timestamp對象。 參數: ts - 要與此時間戳記對象進行比較的時間戳記對象 如果兩個時間戳記對象相等,則返回 值0;如果此Timestamp對象位於給定參數之前,則該值小於0;如果此Timestamp對象位於給定參數之後,則該值大於0。 因爲: 1.4

4
if (!mytime.before(fromtime) && !mytime.after(totime)) 
1
java.util.Date mytime = null; 
if (mytime.after(now) && mytime.before(last_download_time)) 

爲我工作

+1

嗯.. a)這將拋出一個NPE b)只適用於未來的下載,timewarp ;-) – kleopatra

1

可以按如下方式進行排序時間戳:

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

只是轉換時間戳在毫秒錶示。使用getTime()方法。

0

所有這些解決方案對我來說都不起作用,雖然是正確的思維方式。

對我來說,以下工作:

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

之前,我想我想到了您的解決方案與& &太