tags:

views:

29

answers:

3

I have two timestamps recorded on a mysql table using php. How can I calculate the difference between these timestamps in hours using php or mysql?

A: 

in php you can just use regular math and then use the date() function to create the datetime represented in hours

codewrath
A: 

Done in PHP, see this: http://php.about.com/od/advancedphp/qt/math_time_php.htm

Autocracy
A: 

If you actual hours (3600 seconds), it's just a matter of subtracting the timestamps and dividing by 3600:

$hours = ($timestamp2 - $timestamp1)/3600;
$hours = floor($hours); // to round down.

or similar in SQL.

If you want the "logical hours":

$tz = new DateTimezone("Europe/Lisbon"); //replace with actual timezone
$d2 = new DateTime("@$timestamp2");
$d2->setTimezone($tz); 
$d1 = new DateTime("@$timestamp1");
$d1->setTimezone($tz);
$hours = $d2->diff($d1)->h;

This makes difference in case there has been a DST change between the two times. Example:

<?php
$ltz = new DateTimezone("Europe/Lisbon");
date_default_timezone_set("Europe/Lisbon");
$ts2 = strtotime("31-Oct-2010 02:30:00");
$ts1 = strtotime("31-Oct-2010 00:30:00");

$d2 = new DateTime("@$ts2");
$d2->setTimezone($ltz);
$d1 = new DateTime("@$ts1");
$d1->setTimezone($ltz);

var_dump(floor($ts2-$ts1)/3600);
var_dump($d2->diff($d1)->h);

gives:

float(3)
int(2)
Artefacto