因專案需求,需要取得指定日期段內的資料以每日處理。
例如需要對2016-06-01至2016-06-05日期段內,每一天的資料進行處理。首先需要取得這個日期段內每一天日期,再循環執行處理。
<code><span><span><?php</span><span>$date</span> = <span>array</span>(<span>'2016-06-01'</span>,<span>'2016-06-02'</span>,<span>'2016-06-03'</span>,<span>'2016-06-04'</span>,<span>'2016-06-05'</span>); <span>foreach</span>(<span>$date</span><span>as</span><span>$d</span>){ <span>// 执行处理</span> } <span>?></span></span></code>
如果日期段跨度大(2015-09-01至2016-06-30),並且有跨年,跨月(閏月)的情況,人手創建日期數組太費時間且不合理。
因此寫了以下方法,可以取得指定日期段內每一天的日期,程式碼如下:
<code><span><span><span><?php</span> /** * 获取指定日期段内每一天的日期 *<span> @param</span> Date $startdate 开始日期 *<span> @param</span> Date $enddate 结束日期 *<span> @return</span> Array */</span><span><span>function</span><span>getDateFromRange</span><span>(<span>$startdate</span>, <span>$enddate</span>)</span>{</span><span>$stimestamp</span> = strtotime(<span>$startdate</span>); <span>$etimestamp</span> = strtotime(<span>$enddate</span>); <span>// 计算日期段内有多少天</span><span>$days</span> = (<span>$etimestamp</span>-<span>$stimestamp</span>)/<span>86400</span>+<span>1</span>; <span>// 保存每天日期</span><span>$date</span> = <span>array</span>(); <span>for</span>(<span>$i</span>=<span>0</span>; <span>$i</span><<span>$days</span>; <span>$i</span>++){ <span>$date</span>[] = date(<span>'Y-m-d'</span>, <span>$stimestamp</span>+(<span>86400</span>*<span>$i</span>)); } <span>return</span><span>$date</span>; } <span>// demo</span><span>$date</span> = getDateFromRange(<span>'2016-02-25'</span>,<span>'2016-03-05'</span>); print_r(<span>$date</span>); <span>?></span></span></span></code>
輸出:
<code><span>Array</span> ( [<span>0</span>] => <span>2016</span>-<span>02</span>-<span>25</span> [<span>1</span>] => <span>2016</span>-<span>02</span>-<span>26</span> [<span>2</span>] => <span>2016</span>-<span>02</span>-<span>27</span> [<span>3</span>] => <span>2016</span>-<span>02</span>-<span>28</span> [<span>4</span>] => <span>2016</span>-<span>02</span>-<span>29</span> [<span>5</span>] => <span>2016</span>-<span>03</span>-<span>01</span> [<span>6</span>] => <span>2016</span>-<span>03</span>-<span>02</span> [<span>7</span>] => <span>2016</span>-<span>03</span>-<span>03</span> [<span>8</span>] => <span>2016</span>-<span>03</span>-<span>04</span> [<span>9</span>] => <span>2016</span>-<span>03</span>-<span>05</span> )</code>').addClass ('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });
以上就介紹了 php 獲取開始日期與結束日期之間所有日期,包括了方面的內容,希望對PHP教程有興趣的朋友有所幫助。