PHP 获取两个日期相差多少年,多少月,多少天,多少小时,并填充数组

PHP 获取两个日期相差多少年,多少月,多少天,多少小时,并填充数组

<?php

/**
* 获取两个日期相差多少年,多少月,多少天,多少小时,并填充数组
* @param [type] $startTime [开始日期,如:2018-02-10 10:00]
* @param [type] $endTime [结束日期,如:2018-03-01 15:00]
* @param integer $type [单位类型:1小时,2天,3月,4年]
* @return [type] [description]
*/
function getTimesRange($startTime, $endTime, $type = 1)
{
$timeRange = []; $diffRange = diffBetweenTwoDate($startTime, $endTime, $type); switch ($type) {
case 1:
$timeRange[] = date('Y-m-d H:00', strtotime($startTime));
for ($i = 1; $i <= $diffRange['hours']; $i++) {
$timeRange[] = date('Y-m-d H:00', strtotime( date('Y-m-d H:00', strtotime($startTime))
. "+ " . $i . " hours"));
}
break; case 2:
$timeRange[] = date('Y-m-d', strtotime($startTime)); for ($i = 1; $i <= $diffRange['day']; $i++) {
$timeRange[] = date('Y-m-d', strtotime( date('Y-m-d', strtotime($startTime))
. "+ " . $i . " day"));
}
break; case 3:
$timeRange[] = date('Y-m', strtotime($startTime));
for ($i = 1; $i <= $diffRange['month']; $i++) {
$timeRange[] = date('Y-m', strtotime( date('Y-m', strtotime($startTime))
. "+ " . $i . " month"));
}
break; case 4:
       $timeRange[] = intval(date('Y', strtotime($startTime)));
       for ($i = 1; $i <= $diffRange['year']; $i++) {
        $timeRange[] = date('Y', strtotime($startTime)) + $i;
       }
      break;
    }

    return $timeRange;
} /**
* 获取两个日期相差多少年,多少月,多少天,多少小时
* @param [type] $startTime [开始日期,如:2018-02-10 10:00]
* @param [type] $endTime [结束日期,如:2018-03-01 15:00]
*/
function diffBetweenTwoDate($dateOne, $dateTwo)
{
$strtoDateOne = strtotime($dateOne);
$strtoDateTwo = strtotime($dateTwo); if ($strtoDateOne < $strtoDateTwo) {
$tmp = $strtoDateTwo;
$strtoDateTwo = $strtoDateOne;
$strtoDateOne = $tmp;
} $dateMonthOne = explode('-', date('Y-m', $strtoDateOne));
$dateMonthTwo = explode('-', date('Y-m', $strtoDateTwo)); $diff = [];
$diff['hours'] = ($strtoDateOne - $strtoDateTwo) / (60 * 60);
$diff['day'] = ($strtoDateOne - $strtoDateTwo) / (60 * 60 * 24);
$diff['month'] = abs($dateMonthOne[0] - $dateMonthTwo[0]) * 12 + abs($dateMonthOne[1] - $dateMonthTwo[1]);
$diff['year'] = date('Y', $strtoDateOne) - date('Y', $strtoDateTwo); return $diff;
} // 获取两个时间范围,年月日时,并填充数据
$timesRange = getTimesRange('2018-2-10 10:00', '2019-03-01 15:00', 3);
var_dump($timesRange); // 获取两个时间范围,年月日时
$timesRangeCount = diffBetweenTwoDate('2018-2-10 10:00', '2019-03-01 15:00');
var_dump($timesRangeCount);
上一篇:【Qt开发】QScrollArea添加布局后没有出现滚动条的解决方法


下一篇:MVC模式浅谈