PHP:开始日期 - 结束日期范围按月解析

时间:2012-11-02 04:26:22

标签: php mysql

好的,我在这里有一个后勤问题,而不是编码一个,但代码示例/解决方案可能会回答这两个问题,所以这里有...

如果我有一个表单,我用PHP传递了start_date和end_date(m / d / Y格式为完整),我需要打印出一个表格,其中包含mysql数据库中属于该范围的所有条目(所以从m1开始) / d1 / Y1到m2 / d2 / Y2)按月分组,我怎么能以优雅的方式去做呢?

例如,如果我传递start_date = 5/20/2012,end_date = 7/31/2012,我需要结果表以这种格式显示结果:

May 2012  |  June 2012  |  July 2012
....      |  ....       |  .....

2012年5月的第一列将显示来自mysql查询的结果,如

SELECT ... WHERE signup_date >= 5/20/2012 AND signup_date <= 5/31/2012

和2012年6月将同样显示:

SELECT ... WHERE signup_date >= 6/1/2012 AND signup_date <= 6/30/2012

所以我正在寻找一种方法来将开始日期和结束日期解析为从月份的开始日到月末的正确排列的日期数组,如果end_date是几个月后再覆盖所有其他月份之间的完整(从第1个月到最后一个月),以便我可以在for / while循环中循环它们?如下所示:

[0] ['start'] =&gt; '2012年5月20日'

[0] ['end'] =&gt; '2012/5/31'

[1] ['start'] =&gt; '6/1/2012'

[1] ['end'] =&gt; '2012年6月30日'

[2] ['start'] =&gt; '2012年7月1日'

[2] ['end'] =&gt; '7/31/2012'

有什么想法吗?

3 个答案:

答案 0 :(得分:0)

试试这个:

$date = '5/20/2012';
$dateStart = date("m/01/y", strtotime($date));

$start = date("Y-m-d", strtotime($dateStart));
$end = date("Y-m-d", strtotime($dateStart. '+ 1 month - 1 day') );

echo $start;
echo $end;

答案 1 :(得分:0)

你应该用mktime()做到这一点。示例代码如下。

<?php
$startDate = '05/20/2012';
$endDate = '07/31/2012';


$curMonth =  date("m", strtotime($endDate)); //End Month
$curYear = date("Y", strtotime($endDate)); //End Year

$months = array();
$months[] = array('start' => "$curMonth/01/$curYear", 'end' => $endDate);

while ("$curMonth/01/$curYear" > $startDate) {
        $monthEnd =  date("m/d/Y", mktime(0, 0, 0, $curMonth, 0, $curYear));
        $curMonth = date('m', strtotime($monthEnd));
        $curYear = date('Y', strtotime($monthEnd));
        $monthStart = ($curMonth/01/$curYear > $startDate) ? $startDate : "$curMonth/01/$curYear";
        $months[] = array('start' => $monthStart, 'end' => $monthEnd);
}

print_r(($months));
?>

答案 2 :(得分:-1)

首先查看我对mysql db日期格式的评论。

用伪语言写了一点

     $sql="SELECT * FROM ... WHERE `signup_date`>='2012-5-20' AND `signup_date`<'2012-5-31' ORDER BY  `signup_date`";


        $result=mysql_query($sql);

    $month_year=array() //3-dimensional array $month_year[year][month][primary_key];

    $month_index=-1;
    while($row=mysql_fetch_assoc($result)){

    // find $month_of_the_date AND $year_of_the_date

    //find different months ,corresponding years, and db primary key and keep track in the $month_year array




    }

    for( all the years in the array ){

    for(all the corresponding months of the year  in the array){

//**EDIT:** you MIGHT need other loops and arrays to collect distinct years and corresponding months together

    // show the records with the primary keys corresponding to that month and year



    }




    }