簡體   English   中英

從給定的月份中獲得PHP的最后12個月

[英]Get the last 12 months in PHP from Month Year Given

問題:我需要以“ Ym”格式查找兩個給定日期之間的年月字符串。

我有這個,但是不起作用:

for ($i = 0; $i <= 12; $i++) {
    $months[] = date("Y-m%", strtotime(date('Y-m-01') . " -$i months"));
}

因為這是從今天開始的,僅持續12個月。

給定日期的示例:

11-2015 to 05-2018

您可以使用DatePeriod獲取2個DateTimes之間的日期范圍,然后使用DateTime :: format()從這些日期獲取所需的日期字符串(在您的情況下為'Y-m'):

<?php
$dates = new DatePeriod(new DateTime('2015-01'), new DateInterval('P1M'), new DateTime('2018-05'));
$date_strings = array_map(function($d) { return $d->format('Y-m'); }, iterator_to_array($dates));
print_r($date_strings);

得到:

Array
(
    [0] => 2015-01
    [1] => 2015-02
    [2] => 2015-03
    [3] => 2015-04
    [4] => 2015-05
    [5] => 2015-06
    ...
    [39] => 2018-04
)

正確方法:

                $date1=$s_list_102."-".$s_list_101."-01"; //month and year merge on date 1
                $date2=$s_list_104."-".$s_list_103."-01"; //month and year merge on date 1
                $d1 = strtotime($date1);
                $d2 = strtotime($date2);
                $min_date = min($d1, $d2);
                $max_date = max($d1, $d2);
                $c = 0;
                while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
                    $c++;
                }
                for ($i = 0; $i <= $c; $i++) {
                    $months[] = date("M-y", strtotime(date($date2) . " -$i months"));
                }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM