LoginSignup
29
21

More than 5 years have passed since last update.

[PHP] 日時/日付/時間の差を計算する

Last updated at Posted at 2016-02-02

日数部分まで考慮したサンプルが見つからなかったので、日時の差を計算する関数を自作してみました。

PHP5.3以降であれば、DateTimeクラスのdiff()メソッド(またはdate_diff()関数)を利用しての差分計算もできます。
PHP: DateTime::diff

サンプルコード

PHP
<?php
$from = strtotime("-3600 second"); // 現在から3600秒前(=1時間前)
$to   = strtotime("now");          // 現在日時
echo time_diff($from, $to);
// 結果:0days 01:00:00

$from = strtotime("2016-01-01");  // 2016年元旦 (0時0分0秒)
$to   = strtotime("now");         // 現在日時
echo time_diff($from, $to);
// 結果:32days 12:34:56

$from = strtotime("2016-01-01 06:00:00"); // 2016年元旦 6時
$to   = strtotime("2017-01-01 15:00:00"); // 2017年元旦 15時
echo time_diff($from, $to);
// 結果:366days 09:00:00

//***************************************
// 日時の差を計算
//***************************************
function time_diff($time_from, $time_to) 
{
    // 日時差を秒数で取得
    $dif = $time_to - $time_from;
    // 時間単位の差
    $dif_time = date("H:i:s", $dif);
    // 日付単位の差
    $dif_days = (strtotime(date("Y-m-d", $dif)) - strtotime("1970-01-01")) / 86400;
    return "{$dif_days}days {$dif_time}";
}
?>

~ 補足 ~

  • strtotime("now")time() と同等です
  • シンプルなサンプルなので、エラー処理等は考慮してません
  • $time_from < $time_to の大小関係が入れ替わると計算結果がおかしくなってしまうのでご注意下さい(引き算の左右を入れ替えて、マイナス符号を付ければいけるかなと思います)

(・o・ゞ いじょー。

29
21
1

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
29
21