2011-10-27 74 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 

之前,我想我想到了您的解决方案与& &太