How can I compare if a object Date like "2013-12-09 00:00:00" is greater than actual time (System.currentTimeMillis()) in java?
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. It returns the seconds in minute of the Date
instance.
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. 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.
Joda-Time offers the methods isBefore
and isAfter
, just what you need for you comparison.
Your question fails to address time zones. So for my example code below I assumed your given date-time was in UTC /GMT. If that is not the case, then tweak the code by changing the call to withZoneUTC()
to another withZone
method.
// © 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.