Andrea
Andrea

Reputation: 4483

Compare timestamp with actual time (Java)

I've got a time in Timestamp format, it's the expiration time of a product, and I must check if this product is expired. How can I do?

I tried in this way, but actually the function always returns TRUE (I can't figure out why)

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

I think I'm doing a silly mistake, but i can't see it!

Upvotes: 2

Views: 22138

Answers (2)

S.Yavari
S.Yavari

Reputation: 876

Simply use this code:

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

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346270

All you should need is

return expiration_time.before(new Date());

since Timestamp is a subclass of Date

If it doesn't work, then there's something wrong with the value of expiration_time

Upvotes: 7

Related Questions