【问题标题】:php or mysql list dates between range?php或mysql列出范围之间的日期?
【发布时间】:2012-03-31 15:23:45
【问题描述】:

我需要生成一个日期列表(使用 php 或 mysql 或两者都有),其中我指定了开始和结束日期?例如,如果开始日期是 2012-03-31,结束日期是 2012-04-05,我该如何生成这样的列表?

2012-03-31
2012-04-01
2012-04-02
2012-04-03
2012-04-04
2012-04-05

我有一个带有开始和结束日期的 mysql 表,但我需要完整的日期列表。

【问题讨论】:

  • 数据库时间戳的格式是什么?

标签: php mysql


【解决方案1】:

应该这样做:

//Get start date and end date from database

$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$date_list = array($start_date);

$current_time = $start_time;

while($current_time < $end_time) {
    //Add one day
    $current_time += 86400;
    $date_list[] = date('Y-m-d',$current_time);
}
//Finally add end date to list, array contains all dates in order
$date_list[] = $end_date;

基本上,将日期转换为时间戳,并在每个循环中添加一天。

【讨论】:

    【解决方案2】:

    使用 PHP 的 DateTime 库:

    <?php
    
    $start_str = '2012-03-31';
    $end_str = '2012-04-05';
    
    $start = new DateTime($start_str);
    $end = new DateTime($end_str . ' +1 day'); // note that the end date is excluded from a DatePeriod
    
    foreach (new DatePeriod($start, new DateInterval('P1D'), $end) as $day) {
            echo $day->format('Y-m-d'), "\n";
    }
    

    Source

    【讨论】:

      【解决方案3】:

      试试这个:

      <?php
      
        // Set the start and current date
        $start = $date = '2012-03-31';
      
        // Set the end date
        $end = '2012-04-05';
      
        // Set the initial increment value
        $i = 0;
      
        // The array to store the dates
        $dates = array();
      
        // While the current date is not the end, and while the start is not later than the end, add the next day to the array    
        while ($date != $end && $start <= $end)
        {
          $dates[] = $date = date('Y-m-d', strtotime($start . ' + ' . $i++ . ' day'));
        }
      
        // Output the list of dates
        print_r($dates);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 2013-11-23
        • 2020-02-20
        • 2018-08-05
        • 2013-12-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多