比較Date類與System.currentTimeMillis的()我怎樣才能比較,如果像一個對象日期「2013年12月9日00:00:00」比實際時間大於(System.currentTimeMillis的())在java中?我怎樣才能在Java
if (object.getDate().getSeconds() > System.currentTimeMillis())
//do something
比較Date類與System.currentTimeMillis的()我怎樣才能比較,如果像一個對象日期「2013年12月9日00:00:00」比實際時間大於(System.currentTimeMillis的())在java中?我怎樣才能在Java
if (object.getDate().getSeconds() > System.currentTimeMillis())
//do something
呼叫getTime()
,而不是getSeconds()
在Date
對象。
您可以使用if (object.getDate().after(Calendar.getInstance().getTime()) {
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
什麼類型是你的'object'? –
什麼時區是那個日期時間?或者它是[UTC](http://en.wikipedia.org/wiki/Coordinated_Universal_Time)/ GMT? –