Difference between php timestamp? Or mysql timestamp?
I have two timestamps recorded on a mysql table using php. How can I calculate the difference b开发者_JAVA技巧etween these timestamps in hours using php or mysql?
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)
in php you can just use regular math and then use the date() function to create the datetime represented in hours
Done in PHP, see this: http://php.about.com/od/advancedphp/qt/math_time_php.htm
精彩评论