【问题标题】:Php array containing all dates of the current month [closed]包含当月所有日期的 PHP 数组 [关闭]
【发布时间】:2012-11-01 00:50:22
【问题描述】:

我正在尝试但仍然想知道,如何获得一个包含当月所有日期的数组,它应该包含格式为:年-月-日的所有日期。感谢您的帮助!

【问题讨论】:

    标签: php arrays date


    【解决方案1】:

    这个怎么样:

    $list=array();
    for($d=1; $d<=31; $d++)
    {
        $time=mktime(12, 0, 0, date('m'), $d, date('Y'));
        if (date('m', $time)==date('m'))
            $list[]=date('Y-m-d', $time);
    }
    var_dump($list);
    

    【讨论】:

    • 如果月份少于 31 天?
    • 然后它们被 if 跳过。
    • 感谢您的快速回答,正是我所需要的!
    【解决方案2】:

    试试:

    // for each day in the month
    for($i = 1; $i <=  date('t'); $i++)
    {
       // add the date to the dates array
       $dates[] = date('Y') . "-" . date('m') . "-" . str_pad($i, 2, '0', STR_PAD_LEFT);
    }
    
    // show the dates array
    var_dump($dates);
    

    【讨论】:

    • 直截了当,很好。 +1 日期('t')。
    【解决方案3】:

    返回此类数组的简单函数如下所示:

    function range_date($first, $last) {
      $arr = array();
      $now = strtotime($first);
      $last = strtotime($last);
    
      while($now <= $last ) {
        $arr[] = date('Y-m-d', $now);
        $now = strtotime('+1 day', $now);
      }
    
      return $arr;
    }
    

    如果需要,您可以通过将步骤 (+1 day) 和输出格式 (Y-m-d) 更改为可选参数来改进它。

    【讨论】:

    • 最适合我有开始和结束日期的情况,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    相关资源
    最近更新 更多