找到2个java.sql.Timestamps之间的小时或分钟差异?

时间:2012-05-14 06:54:43

标签: java

我将java.sql.Timestamp存储在 postgresql 数据库中作为时间戳数据类型,我想找出与存储的数据类型相差几分钟或几小时的差异DB到当前的时间戳。这样做的最佳方法是什么?有没有内置的方法,或者我必须将它转换成长或什么?

6 个答案:

答案 0 :(得分:20)

我结束了这个,如果他们搜索它,只想发布给其他人。

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;
}

答案 1 :(得分: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();
}

“field”的示例:Calendar.HOUR_OF_DAY,Calendar.MINUTE

答案 2 :(得分:1)

只需使用:

Date.compareTo(Date) 

您必须先将java.sql.Timestamps转换为Date。

答案 3 :(得分:0)

使用UNIX_TIMESTAMP功能将DATETIME转换为小时,分钟和秒的值 如果您不确定哪个值更大,请使用ABS功能。

答案 4 :(得分:0)

date_part函数可以为您提供hours或者感兴趣但是,它是substr的一种,因此不能依赖它。您需要将timestamp值转换为unix_timestampextract 经过的小时数,分钟数或自timestamp到{{current_timestamp以来的任何相关内容1}}。

示例

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.

epochextract 一起使用:

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                |  
----------------+--------------+-----------------------  

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

答案 5 :(得分:0)

使用它,它非常准确:

    long diff = end - start;

    long diffDays = diff / (24 * 60 * 60 * 1000);
    long remain = diff % (24 * 60 * 60 * 1000);

    long diffHours = remain / (60 * 60 * 1000);
    remain = remain % (60 * 60 * 1000);

    long diffMinutes = remain / (60 * 1000);
    remain = remain % (60 * 1000);

    long diffSeconds = remain / (1000);

    System.out.println("days : " + diffDays);
    System.out.println("hours : " + diffHours);
    System.out.println("minutes : " + diffMinutes);
    System.out.println("secs: " + diffSeconds2);