2012-05-14 67 views
10

我在的PostgreSQL數據庫存儲java.sql.Timestamp時間戳數據類型,我想找出從存儲在數據庫中,以當前時間戳了一個在幾分鐘或幾小時的差異。這樣做的最好方法是什麼?有沒有建立在它的方法或我必須將其轉換爲長或什麼?查找2個java.sql.Timestamps之間的小時或分鐘差異?

+0

的可能重複[如何計算兩個Java java.sql.Timestamps之間的區別?(http://stackoverflow.com/questions/582278/how-to-calculate-the-difference-between- two-java-java-sql-timestamps) –

回答

17

我結束使用這個,只是想發佈給他人,如果他們搜索它。

public static long compareTwoTimeStamps(java.sql.Timestamp currentTime, java.sql.Timestamp oldTime) 
{ 
    long milliseconds1 = oldTime.getTime(); 
    long milliseconds2 = currentTime.getTime(); 

    long diff = milliseconds2 - milliseconds1; 
    long diffSeconds = diff/1000; 
    long diffMinutes = diff/(60 * 1000); 
    long diffHours = diff/(60 * 60 * 1000); 
    long diffDays = diff/(24 * 60 * 60 * 1000); 

    return diffMinutes; 
} 
+0

你是最棒的! – dbrad

0

使用UNIX_TIMESTAMP函數將DATETIME轉換爲以小時,分鐘和秒爲單位的值。
如果您不確定哪個值更大,那麼使用ABS功能。

1

對於日期添加/刪除這是我的泛型函數:

public static Date addRemoveAmountsFromDate(Date date, int field, int amount) { 
    Calendar tempCalendar = Calendar.getInstance(); 

    tempCalendar.setTime(date); 
    tempCalendar.add(field, amount); 

    return tempCalendar.getTime(); 
} 

例如對 「現場」:Calendar.HOUR_OF_DAY,Calendar.MINUTE

1

只需使用:

Date.compareTo(Date) 

你必須先將java.sql.Timestamps轉換爲Date。

+0

OP希望以小時和分鐘的形式查找到目前爲止的時間,但如果日期相等,則前或後都不會。 –

+0

這個答案與問題無關 –

0

date_part功能可以給你hours或作爲利益可能是,但它是一種substr,因此不能依靠它。您需要將您的timestamp值轉換爲unix_timestampextract總計經過的小時數,分鐘數或自timestampcurrent_timestamp以來的任何相關值。

select age(now(), timestamp '2010-11-12 13:14:15'); 
//results the interval to be "*1 year 6 mons 2 days 04:39:36.093*" 

select date_part('hours', age(now(), timestamp '2010-03-10 02:03:04')); 
// results *4* which is not correct. 

的小時或他人正確值可以找到的自1970年以來經過的秒數這可以通過使用與epoch功能extract來實現總數後進行計算。
epoch返回自1970-01-01 00:00:00-00以來的總秒數。而且,你知道,我們可以把它與3600

使用epoch將它與extract轉換成時間:

select 
    EXTRACT(EPOCH FROM current_timestamp - timestamp '2010-11-12 13:14:15') as total_seconds, 
    EXTRACT(EPOCH FROM current_timestamp - timestamp '2010-11-12 13:14:15')/3600 as total_hours; 
    ROUND( 
     EXTRACT(EPOCH FROM current_timestamp - timestamp '2010-11-12 13:14:15')/3600 
     ) as total_hours_rounded; 

//結果:

----------------+--------------+----------------------- 
| total_seconds | total_hours | total_hours_rounded | 
| --------------+--------------+----------------------| 
| 47452282.218 | 13181.189505 | 13181    | 
----------------+--------------+----------------------- 

同樣,我們可以提取其他所需的值並根據需要使用。