2012-05-14 65 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    | 
----------------+--------------+----------------------- 

同样,我们可以提取其他所需的值并根据需要使用。