如何在php中的2个日期范围之间逐月计数

时间:2013-12-27 09:12:32

标签: php

我正在尝试计算PHP中两个给定日期之间的月份总数。

开始日期='2011-02-01'
结束日期='2013-04-10'

Result :
Year : Month
2011 : 10
2012 : 12
2013 : 4

2 个答案:

答案 0 :(得分:3)

$startDate = '2011-02-01';
$endDate = '2013-04-10';
$results = array();

while (true) {
    $startDate = date('Y-m-d', strtotime($startDate . ' + 1 month'));

    if ($startDate >= $endDate) break;

    $year = date('Y', strtotime($startDate));

    if (!isset($results[$year])) {
        $results[$year] = 0;
    }

    $results[$year]++;
}


print_r($results);
// Array ( [2011] => 10 [2012] => 12 [2013] => 4 )

已编辑:将结果插入数据库。

foreach ($results as $year => $monthCount) {
    $sql = "
        INSERT INTO `your_table_name`(`year`, `month_count`)
        VALUES ('{$year}', '{$monthCount}')
    ";
    // Use $sql with your DB adapter
}

答案 1 :(得分:1)

试试这个

<?php

$start_date = strtotime('2011-02-01');
$end_date = strtotime('2013-04-10');
$diff = $end_date - $start_date;

$result = Sec2Time($diff);
print_r($result);

function Sec2Time($time){
  if(is_numeric($time)){
    $value = array(
      "years" => 0, "months" => 0, "days" => 0, "hours" => 0,
      "minutes" => 0, "seconds" => 0,
    );
    if($time >= 31556926){
      $value["years"] = floor($time/31556926);
      $time = ($time%31556926);
    }
    if($time >= 2628000){
      $value["months"] = floor($time/2628000);
      $time = ($time%2628000);
    }
    if($time >= 86400){
      $value["days"] = floor($time/86400);
      $time = ($time%86400);
    }
    if($time >= 3600){
      $value["hours"] = floor($time/3600);
      $time = ($time%3600);
    }
    if($time >= 60){
      $value["minutes"] = floor($time/60);
      $time = ($time%60);
    }
    $value["seconds"] = floor($time);
    return (array) $value;
  }else{
    return (bool) FALSE;
  }
}
?>