PHP在X日期和X日期之间分为几个月

时间:2018-07-22 08:03:39

标签: php date datetime strtotime

做出报告:

用户输入的2个日期:例如开始时间:04-03-12结束时间:15-06-12

$ROStartDateTimestamp = strtotime('04-03-12');
$ROStartDate = date('d/m/Y', $ROStartDateTimestamp);
$ROEndDateTimestamp = strtotime('15-06-12');
$ROEndDate = date('d/m/Y', $ROEndDateTimestamp);

我想把时间分成几个月。

我如何找出答案;

  1. 开始月份有几天?
  2. 开始月份的最后一天的日期是什么?
  3. 开始日期到该月末之间有多少天?

感谢Heep的:)

2 个答案:

答案 0 :(得分:0)

您可以循环它并创建一个数组,以后可以与count或array_sum一起使用。

我创建了一个多维数组,其中包含年月日和起始日与结束日之间的所有日期。

$start = strtotime('04-03-12');
$end = strtotime('15-06-12');

For($i = $start; $i<=$end;){
    List($y, $m, $d) = explode(" ", date("Y m d", $i));
    $arr[$y][$m][$d] = 1;
    $i += 86400;
}

Var_dump($arr);

使用DateTime可以完成相同的操作,但通常使用起来比较麻烦,这就是为什么我使用strtotime。
https://3v4l.org/1m8aM

答案 1 :(得分:0)

$ROStartDateTimestamp = strtotime('04-03-12');
$ROStartDate = date('d/m/Y', $ROStartDateTimestamp);
$ROEndDateTimestamp = strtotime('15-06-12');
$ROEndDate = date('d/m/Y', $ROEndDateTimestamp);

//To find month in start date:
$ROMonthofStartDate = date('m',$ROStartDateTimestamp);

//To find year in start date:
$ROYearofStartDate = date('Y',$ROStartDateTimestamp);

//To find number of days in a month:
$numDaysInMonthofStartDate=cal_days_in_month(CAL_GREGORIAN,$ROMonthofStartDate,$ROYearofStartDate);

//To find last date of month:
$lastDateInMonthofStartDate=date('Y-m-t',$ROStartDateTimestamp);
$lastDateTimestamp = strtotime($lastDateInMonthofStartDate);

//To find number of days from start date to the end of month:
$numDaysFromStartToEndDate = round( ($lastDateTimestamp-$ROStartDateTimestamp) / (60 * 60 * 24));

echo $numDaysFromStartToEndDate;