2

我在我的 php 脚本中使用时间戳来处理以小时、分钟和秒为单位的时间。时间戳也记录日期,但我只使用 time 00:00:00

例如,我正在计算时间差

$start = strtotime("12:00:00");
$end = strtotime("20:00:00");

$difference = $end - $start;

或划分时间

$divide = $difference/3;

我应该继续为这些操作使用时间戳还是 php 中有特定时间的函数?

4

5 回答 5

10

如何做到这一点的一个例子DateTime

$d1 = new DateTime('11:00:00');
$d2 = new DateTime('04:00:00');

$diff = $d1->diff($d2);

echo $diff->h, " hours ", $diff->i, " minutes\n";

输出:

7 hours 0 minutes
于 2012-06-07T04:17:54.627 回答
1

There is no time specific standard function in php as far as I know, what you are doing is fine. However, it is fairly easy to do the calculation on your own.

$newHour = $hour1-$hour2;
$newMinute = $minute1 - $minute2;
if($newMinute < 0 ){
    $newMinute +=60;
    $newHour--;
}
$newSecond = $second1 - $second2;
if($newSecond < 0){
    $newMinute --;
    $newSecond +=60;

}

Assuming the first date is later than the second this should work just fine

于 2012-06-07T04:12:17.240 回答
1

You could use mktime. You can call it that way:

$time1 = mktime(12,24,60);   // hour,minute,second
$time2 = mktime(16,24,60);
echo ($time2 - $time1);

the results are seconds, like time() and strtotime()

于 2012-06-07T04:13:58.087 回答
1

If timestamps suit you, then continue using them. There really isn't anything wrong with them (except the unix version of Y2K in 2038 when the timestamp will no longer fit in a 32bit int). PHP alternatively gives you another way to do time calculations with the DateTime class

于 2012-06-07T04:14:41.637 回答
0

您应该使用DateTime可以计算两个时间点之间差异的类。

$d1 = new DateTime('11:00:00');
$d2 = new DateTime('04:00:00');

$diff = $d1->diff($d2);

echo $diff->h, " hours ", $diff->i, " minutes\n";
于 2021-01-07T09:15:55.270 回答