by shigemk2

当面は技術的なことしか書かない

2つの日付の差を求める

PHP による日付・時刻・時間の計算・演算のまとめ - hoge256ブログ

<?php
/**
 * 2つの日付の差を求める関数
 * $year1 1つのめ日付の年
 * $month1 1つめの日付の月
 * $day1 1つめの日付の日
 * $year2 2つのめ日付の年
 * $month2 2つめの日付の月
 * $day2 2つめの日付の日
 */
function compareDate($year1, $month1, $day1, $year2, $month2, $day2) {
    $dt1 = mktime(0, 0, 0, $month1, $day1, $year1);
    $dt2 = mktime(0, 0, 0, $month2, $day2, $year2);
    $diff = $dt1 - $dt2;
    $diffDay = $diff / 86400;//1日は86400秒
    return $diffDay;
}

//2007年8月9日と2007年7月9日の差を求める
//31が表示されます
$days = compareDate(2007, 8, 9, 2007, 7, 9);
print("2007-08-09 - 2007-07-09 = {$days} days<br />\r\n");

//2007年1月10日と2006年10月10日の差を求める
//92が表示される
$days = compareDate(2007, 1, 10, 2006, 10, 10);
print("2007-01-10 - 2006-10-10 = {$days} days<br />\r\n");

という感じだが、例えば2012-01-01から$year1とか$month2とかを
手動で取り出すのはしんどいので、'YYYY-MM-DD'や'YYYY-MM-DD HH:II:SS'から
必要なyear と month と day を取り出す関数を用意して、
こんな風に改造してみてはどうだろうか。

<?php
function substrDate($date, &$year, &$month, &$day) {
  // 一応引数チェックをここでやる
  $match = '/^\d{4}\-\d{2}\-\d{2}\s+\d{2}\:\d{2}\:\d{2}|^\d{4}\-\d{2}\-\d{2}/';
  if(!preg_match($match, $date)) {
    return;
  }
  $year = substr($date, 0, 4);
  if(substr($date, 5, 1) == 0) {
    $month = substr($date, 6, 1);
  } else {
    $month = substr($date, 5, 2);
  }
  if(substr($date, 8, 1) == 0) {
    $day = substr($date, 9, 1);
  } else {
    $day = substr($date, 8, 2);
  }
}

// 日数比較関数の改良版('YYYY-MM-DD' もしくは 'YYYY-MM-DD HH:II:SS')
function compareDate($date1, $date2) {
  substrDate($date1, $year1, $month1, $day1);
  substrDate($date2, $year2, $month2, $day2);
  $date1time = mktime(0, 0, 0, $month1, $day1, $year1);
  $date2time = mktime(0, 0, 0, $month2, $day, $year2);
  $diff_day =  ($date2time - $date1time)/(60*60*24);
  return $diff_day;
}

$days = compareDate('2007-01-10', '2006-10-10');
print("2007-01-10 - 2006-10-10 = {$days} days<br />\r\n");

date型のデータを渡したら、あとはよろしくやってくれる感じで。