Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find hour or minute difference between 2 java.sql.Timestamps?

Tags:

java

I store a java.sql.Timestamp in a postgresql database as Timestamp data type and I want to find out the difference in minutes or hours from the one stored in the DB to the current timestamp. What is the best way about doing this? are there built in methods for it or do I have to convert it to long or something?

like image 946
Arya Avatar asked May 14 '12 06:05

Arya


People also ask

How do I get the time difference between two timestamps in SQL?

To calculate the difference between the timestamps in MySQL, use the TIMESTAMPDIFF(unit, start, end) function. The unit argument can be MICROSECOND , SECOND , MINUTE , HOUR , DAY , WEEK , MONTH , QUARTER , or YEAR .

How do you find the difference between two timestamps in an hour?

To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.

How do you find the difference between two timestamps?

The difference is calculated by subtracting the second operand from the first. The result is rounded down, with any remainder discarded. For example, 61 minutes is equal to 1 hour, and 59 minutes is equal to 0 hours.

Can we compare two timestamps?

When comparing two TIMESTAMP WITH TIME ZONE values, the comparison is made using the UTC representations of the values. Two TIMESTAMP WITH TIME ZONE values are considered equal if they represent the same instance in UTC, regardless of the time zone offsets that are stored in the values. For example, '1999-04-15-08.00.


1 Answers

I ended using this, just want to post it for others if they search for it.

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;
}
like image 102
Arya Avatar answered Oct 04 '22 13:10

Arya