[英]How can I compare Date class with System.currentTimeMillis() in java
How can I compare if a object Date like "2013-12-09 00:00:00" is greater than actual time (System.currentTimeMillis()) in java? 如何比较Java中类似“ 2013-12-09 00:00:00”的对象日期是否大于实际时间(System.currentTimeMillis())?
if (object.getDate().getSeconds() > System.currentTimeMillis())
//do something
您可以使用if (object.getDate().after(Calendar.getInstance().getTime()) {
在Date
对象中调用getTime()
而不是getSeconds()
。
getSeconds
doesn't return the amount of seconds since epoch. getSeconds
不会返回自纪元以来的秒数。 It returns the seconds in minute of the Date
instance. 它返回
Date
实例的秒数(以分钟为单位)。
So I guess that what you need is: 所以我想您需要的是:
if (object.getDate().getTime() > System.currentTimeMillis())
You should depend on a good date-time library rather than doing your own math with System milliseconds. 您应该依靠一个好的日期时间库,而不是用系统毫秒数来进行自己的数学运算。
In Java now (year 2013), that means Joda-Time 2.3. 在现在的Java(2013年)中,这表示Joda-Time 2.3。 In Java 8, consider moving to the new java.time.* classes from JSR 310. Those classes are inspired by Joda-Time but are entirely re-architected.
在Java 8中,请考虑从JSR 310移到新的java.time。*类。这些类的灵感来自Joda-Time,但已完全重新构造。
Joda-Time offers the methods isBefore
and isAfter
, just what you need for you comparison. Joda-Time提供了
isBefore
和isAfter
方法,正是您进行比较所需的方法。
Your question fails to address time zones. 您的问题未能解决时区问题。 So for my example code below I assumed your given date-time was in UTC /GMT.
因此,对于下面的示例代码,我假设您给定的日期时间是UTC / GMT。 If that is not the case, then tweak the code by changing the call to
withZoneUTC()
to another withZone
method. 如果不是这种情况,则通过
withZoneUTC()
的调用更改为另一个withZone
方法来调整代码。
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss" );
DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( "2013-12-09 00:00:00" );
DateTime now = new DateTime();
Boolean isFuture = ( dateTimeInUTC.isAfter( now ) );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "now: " + now );
System.out.println( "now in UTC: " + now.toDateTime( DateTimeZone.UTC ) );
System.out.println( "isFuture: " + isFuture );
When run… 运行时...
dateTimeInUTC: 2013-12-09T00:00:00.000Z
now: 2013-12-09T23:46:05.902-08:00
now in UTC: 2013-12-10T07:46:05.902Z
isFuture: false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.