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?
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 .
To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With