[英]How can I compare Date class with 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
不会返回自纪元以来的秒数。 它返回Date
实例的秒数(以分钟为单位)。
所以我想您需要的是:
if (object.getDate().getTime() > System.currentTimeMillis())
您应该依靠一个好的日期时间库,而不是用系统毫秒数来进行自己的数学运算。
在现在的Java(2013年)中,这表示Joda-Time 2.3。 在Java 8中,请考虑从JSR 310移到新的java.time。*类。这些类的灵感来自Joda-Time,但已完全重新构造。
Joda-Time提供了isBefore
和isAfter
方法,正是您进行比较所需的方法。
您的问题未能解决时区问题。 因此,对于下面的示例代码,我假设您给定的日期时间是UTC / GMT。 如果不是这种情况,则通过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 );
运行时...
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.