php working with time only

2019-04-02 02:38发布

I'm using timestamp in my php script to handle time in hours, minutes and seconds. Timestamps also record the date but I'm only using time 00:00:00.

For instance I'm caluclate difference in time

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

$difference = $end - $start;

or dividing time

$divide = $difference/3;

Should I continue using timestamps for these operations or is there a time-specific function in php?

标签: php date time
4条回答
淡お忘
2楼-- · 2019-04-02 02:56

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()

查看更多
欢心
3楼-- · 2019-04-02 02:59

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

查看更多
地球回转人心会变
4楼-- · 2019-04-02 03:08

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

查看更多
聊天终结者
5楼-- · 2019-04-02 03:09

An example of how to do this with 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";

Output:

7 hours 0 minutes
查看更多
登录 后发表回答