如何按月划分日期

时间:2017-10-13 11:11:47

标签: php datetime

两个日期13-10-201713-02-2018。我想在几个月内将这段时间分开,例如13-10-2017 to 31-10-2-1701-11-2017 to 30-11-201701-12-2017 to 31-12-201701-01-2018 to 31-01-201801-02-2018 to 13-02-2018。我做了什么我可以在日期期间获得月份名称,但不是我想要的格式。

这是我的代码:

$start_date = new DateTime('13-10-2017');
$end_date = new DateTime('13-02-2018');
$date_interval = new DateInterval('P1M');
$date_period   = new DatePeriod($start_date, $date_interval, $end_date);
# calculating number of days in the interval
$interval  = $start_date->diff( $end_date );
$days = $interval->days;
# getting names of the months in the interval
$month_count = 0;
$month_names = array();
foreach ($date_period as $date) {
    $month_names[] = $date->format('F');
    $month_count++;
}
$month_name_string = implode(',', $month_names);
echo $start_date->format('d-m-Y').' to '.$end_date->format('d-m-Y'). ' is ' .$days.' days and month names are: '.$month_name_string;

我得到的输出:

13-10-2017 to 13-02-2018 is 123 days and month names are: October,November,December,January

2 个答案:

答案 0 :(得分:1)

您可以使用DateTime::modify功能。 E.g:

$month_intervals = [];
foreach ($date_period as $date) {
    $start = $date == $start_date ? $start_date : $date->modify('first day of this month');
    $month_intervals[] = join([
        $start->format('d-m-Y'),
        $date->modify('last day of this month')->format('d-m-Y')
    ], ' to ');
}
$month_intervals[] = join([
    (clone $end_date)->modify('first day of this month')->format('d-m-Y'),
    $end_date->format('d-m-Y')
], ' to ');
echo implode(',', $month_intervals);

答案 1 :(得分:1)

您可以在迭代时执行以下检查:

  • 如果当前月份位于$start_date,请使用其当天作为开始日期
  • 如果当前月份在$end_date,请使用当天的最后一天
  • 否则,请使用每月的1天和最长日期(使用t format character

此外,您需要在最后一天将时间设置为00:00:01,以便在DateInterval中考虑:

<?php
$start_date = new DateTime('13-10-2017');
$end_date = new DateTime('13-02-2018');
$end_date->setTime(0, 0, 1); // important, to consider the last day!
$date_interval = new DateInterval('P1M');
$date_period   = new DatePeriod($start_date, $date_interval, $end_date);
# calculating number of days in the interval
$interval  = $start_date->diff( $end_date );
$days = $interval->days;
# getting names of the months in the interval
$dates = [];
foreach ($date_period as $date) {
    $dateArr = [];
    if ($date->format("Y-m") === $start_date->format("Y-m")) {
        $dateArr["start"] = $start_date->format("d-m-Y");
    }
    else {
        $dateArr["start"] = $date->format("01-m-Y");
    }
    if ($date->format("Y-m") === $end_date->format("Y-m")) {
        $dateArr["end"] = $end_date->format("d-m-Y");
    }
    else {
        $dateArr["end"] = $date->format("t-m-Y"); // last day of the month
    }
    $dates[] = $dateArr;
}
foreach ($dates as $date) {
    echo $date["start"]." to ".$date["end"].PHP_EOL;
}

Demo