php - 如何在php中获取给定日期范围内月份的开始日期和结束日期

标签 php datetime date

我使用以下代码来显示当月的开始和结束日期。

function firstOfMonth() {
return date("m/d/Y", strtotime(date('m').'/01/'.date('Y').' 00:00:00'));
}

function lastOfMonth() {
return date("m/d/Y", strtotime('-1 second',strtotime('+1 month',strtotime(date('m').'/01/'.date('Y').' 00:00:00'))));
}

$date_start = firstOfMonth();
$date_end  = lastOfMonth();
echo $date_start;
echo $date_end;

问题:如何获取给定日期范围内所有月份的开始日期和结束日期

例如:

function daterange($startdate,$enddate)
{
...
...
...
}

预期结果是 $startdate$enddate 日期范围之间每个月的开始日期和结束日期的数组。

帮我看看该怎么做......

最佳答案

<?php
//Function to return out start and end dates of all months in a date range given

function rent_range($start_date, $end_date)
{
    $start_date = date("m/d/Y", strtotime($start_date));
    $end_date   = date("m/d/Y", strtotime($end_date));
    $start = strtotime($start_date);
    $end = strtotime($end_date);

    $month = $start;
    $months[] = date('Y-m', $start);
    while($month < $end) {
      $month = strtotime("+1 month", $month);
      $months[] = date('Y-m', $month);
    }

    foreach($months as $mon)
    {
        $mon_arr = explode( "-", $mon);
        $y = $mon_arr[0];
        $m = $mon_arr[1];
        $start_dates_arr[] = date("m/d/Y", strtotime($m.'/01/'.$y.' 00:00:00'));
        $end_dates_arr[] = date("m/d/Y", strtotime('-1 minute', strtotime('+1 month',strtotime($m.'/01/'.$y.' 00:00:00'))));
    }

    //to remove first month in start date and add our start date as first date
    array_shift($start_dates_arr);
    array_pop($start_dates_arr);
    array_unshift($start_dates_arr, $start_date);

    //To remove last month in end date and add our end date as last date
    array_pop($end_dates_arr);
    array_pop($end_dates_arr);
    array_push($end_dates_arr, $end_date);

    $result['start_dates'] = $start_dates_arr;
    $result['end_dates'] = $end_dates_arr;
    return $result;
}

$start_date = '2011-07-29';
$end_date = '2012-03-31';
$res = rent_range($start_date, $end_date);
echo "<pre>";
print_r($res);
echo "</pre>";
?>

我的上述函数将给出给定范围内日期的月份范围显示。 这个函数对于印度传统的月租金计算很有用。

这可能对其他人有帮助......

关于php - 如何在php中获取给定日期范围内月份的开始日期和结束日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6612256/

相关文章:

php - 单独的数组值 PHP

php - 如何向两个不同的用户发送两个不同的消息phpmailer

php - 检查我的数据库 php 中两次之间的值

python - 使用 Python 将字符串转换为格式化的日期时间字符串

python pandas时间序列年提取

php - 将php mysql时间转换为秒前

r - 根据日期差异创建新列

php - 在 Woocommerce 3 中添加和管理产品自定义上传字段

java - JodaTime - 2 个日期之间每月的天数

perl - 无法安装 Date::Manip perl 模块。不断收到 cpanmetadb 错误