LoginSignup
2
4

PHPで時間計算

Last updated at Posted at 2020-10-02

勤務時間など算出したいときに「PHP 時間 計算」と調べていたのですが、検索上位に出てくるのがどうしても「日時の計算」で出てきてしまうため、自身の備忘として。

Code

例えば10:00から18:00まで仕事をしたときの勤務時間を算出。

time_diff.php
<?php

$Date = date("Y-m-d");
$InTime = $Date." 10:00:00";
$OutTime = $Date." 18:00:00;

$WorkTime = (strtotime($OutTime) - strtotime($InTime))/3600; 

?>

これで$WorkTimeをechoしてあげれば「8」と表示されるはずです。
小数点以下第一位まで出したい場合は

echo number_format($WorkTime, 1);

としてあげれば良いです。

計算詳細

計算内容を見ていきます。

strtotimeは英文形式の日付をUnixタイムスタンプに変換します。
(ひとまずdateでその日の年月日を取得しているので、日付は投稿日の2020/10/02とします)

strtotime($InTime) = 1601600400
strtotime($OutTime) = 1601629200

これを引き算。

strtotime($OutTime) - strtotime($InTime) = 1601629200 - 1601600400 = 28800

Unixタイムスタンプなので、単位は「秒」です。
なので、これを時間に直すために3600で除算します。

28800 / 3600 = 8

※参考URL
[PHP]strtotime
https://www.php.net/manual/ja/function.strtotime.php

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4