[英]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.