我在我的 php 脚本中使用时间戳来处理以小时、分钟和秒为单位的时间。时间戳也记录日期,但我只使用 time 00:00:00
。
例如,我正在计算时间差
$start = strtotime("12:00:00");
$end = strtotime("20:00:00");
$difference = $end - $start;
或划分时间
$divide = $difference/3;
我应该继续为这些操作使用时间戳还是 php 中有特定时间的函数?
如何做到这一点的一个例子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
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
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()
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
您应该使用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";