2013-10-15 49 views
4

我想比較一個類中的Time實例與當前系統時間。我正在使用beforeafter方法,但它提供了意想不到的結果。如何比較Time.sql

Time currentSystemTime = new Time(new java.util.Date().getTime()); 
Time t = Time.valueOf("23:25:00"); 
System.out.println(currentSystemTime+" currentTime"); 
System.out.println(t+" hardcoded Time"); 

輸出

21:24:48 currentTime 
23:25:00 hardcoded Time 

但現在,如何比較這些都times.I我嘗試following.It不工作。

if(currentSystemTime.before(t)) 
{ 
    System.out.println("Hello"); 
} 

這個hello應該執行,但它不是。有沒有什麼辦法比較時間。

回答

-1

通過調用getTime()可以獲得以毫秒爲單位的時間。 現在比較一個和另一個,這樣你可以在之前或之後得到。

1

這是因爲他們在不同年份,

public static void main(String[] args) { 
     Time currentSystemTime = new Time(new java.util.Date().getTime()); 
     Time t = Time.valueOf("23:25:00"); 
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
     System.out.println(currentSystemTime + " currentTime"); 
     System.out.println(t + " hardcoded Time"); 
     System.out.println(sdf.format(currentSystemTime)); 
     System.out.println(sdf.format(t)); 
     if (currentSystemTime.before(t)) { 
      System.out.println("Hello"); 
     } 
    } 

結果...

17:04:13 currentTime 
23:25:00 hardcoded Time 
2013-10-15T17:04:13.758+0100 
1970-01-01T23:25:00.000+0100 

原因的getTime()會工作作爲@barwinkk提到是它返回的長期表現從1970年1月1日00:00:00開始,以此Date對象表示的毫秒數。

+0

更好的是time.getTime() – barwnikk

+0

我證明了爲什麼OP認爲他得到了錯誤的結果。 – david99world

+0

你對這一年的爭論是無效的 - 'Time'對象允許你比較時間忽略'Date'的日期部分。 – mazaneicha

-1
Time currentSystemTime = new Time(new java.util.Date().getTime()); 
Time t = Time.valueOf("23:25:00"); 
System.out.println(currentSystemTime+" currentTime"); 
System.out.println(t+" hardcoded Time"); 
if(currentSystemTime.getTime()<t.getTime()) 
{ 
    System.out.println("Hello"); 
}