将时间戳与实际时间进行比较(Java)

时间:2013-01-12 10:34:51

标签: java date timestamp

我有Timestamp格式的时间,这是产品的到期时间,我必须检查此产品是否已过期。 我该怎么办?

我试过这种方式,但实际上函数总是返回TRUE(我无法弄清楚原因)

public boolean isAuctionExpired() {

    // expiration_time is setted before, is the expiration date of a product!

    Timestamp actualTimeStampDate = null;

    try {
        Date actual = new Date();
        actualTimeStampDate = new Timestamp(actual.getTime());
    } catch (Exception e) {
        System.out.println("Exception :" + e);
    }

    boolean expired = (expiration_time.getTime() < actualTimeStampDate.getTime());

    // Everything seems ok, except the boolean
    System.out.println("product exp: "+expiration_time+", actual: "+actualTimeStampDate+" expired? "+expired);

    return expired;
}

我认为我犯了一个愚蠢的错误,但我看不到它!

2 个答案:

答案 0 :(得分:6)

你需要的只是

return expiration_time.before(new Date());

因为TimestampDate

的子类

如果它不起作用,则expiration_time

的值有问题

答案 1 :(得分:0)

只需使用此代码:

public boolean isAuctionExpired() {
    return expiration_time.getTime() <= System.currentTimeMillis();
}