在Java中比较两个时间戳

52

如何比较 mytime 是否在 fromtimetotime 之间:

Timestamp fromtime;
Timestamp totime;

Timestamp mytime;
9个回答

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

考虑莫里斯·佩里的回应,如果您想包括 fromTimetoTime - Ahmed Ashour

19

使用beforeafter方法:Javadoc

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

13

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

public int compareTo(Timestamp ts)

比较此Timestamp对象与给定的Timestamp对象。 参数: ts - 要与此Timestamp对象进行比较的Timestamp对象 返回值: 如果两个Timestamp对象相等,则返回值为0;如果此Timestamp对象在给定参数之前,则返回小于0的值;如果此Timestamp对象在给定参数之后,则返回大于0的值。 自: 1.4


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

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

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

对我很有用


1
哦,a) 那会抛出 NPE b) 只对未来下载有效,时空扭曲;-) - kleopatra
现在在 if (mytime.after(now)) 中是什么? - PTT

1

Timestampafterbefore方法可以解决这个问题。


损坏的链接。 - Skynet

0

所有这些解决方案对我都不起作用,尽管思考方式是正确的。

以下方法适用于我:

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

在我尝试之前,我也考虑过你使用 && 的解决方案


-3

只需将时间戳转换为毫秒表示法。使用getTime()方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接