比较时间戳与实际时间(Java)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14292463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare timestamp with actual time (Java)
提问by Andrea
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?
我有Timestamp
格式时间,它是一个产品的过期时间,我必须检查这个产品是否过期。我能怎么做?
I tried in this way, but actually the function always returns TRUE (I can't figure out why)
我这样试过,但实际上函数总是返回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;
}
I think I'm doing a silly mistake, but i can't see it!
我想我犯了一个愚蠢的错误,但我看不到它!
回答by Michael Borgwardt
All you should need is
所有你应该需要的是
return expiration_time.before(new Date());
since Timestamp
is a subclass of Date
因为Timestamp
是的子类Date
If it doesn't work, then there's something wrong with the value of expiration_time
如果它不起作用,则说明的值有问题 expiration_time
回答by S.Yavari
Simply use this code:
只需使用此代码:
public boolean isAuctionExpired() {
return expiration_time.getTime() <= System.currentTimeMillis();
}