从PHP当月获取月份名称 - 到年底

从PHP当月获取月份名称 - 到年底

问题描述:

I have fetched a current month from my DB which is basically a join date of the user. Lets say the use joined this month and it is May. The code I do to fetch the month name is like this:

$months = array();
array_push($months,date("F",strtotime($me['joinTime'])));

In this case I add the start month to the array, which in this case is May... Now what I'd like to do is as the months go by, I'd like to add each new month to the array.. So for instance in a few days its June, and when June kicks in, I'll add that Month as well to the array.. So my question here is, how can I get the rest of the month names from the start date (May).

I need June, July, August, September, October, November, December...

If the start month was April I'd add May into the array as well...

Can someone help me out with this ?

我从我的数据库中获取了当前月份,这基本上是用户的加入日期。 让我们说本月使用的是加入,也就是五月。 我用来获取月份名称的代码是这样的: p>

  $ months = array(); 
array_push($ months,date(“F”,strtotime($ me)  ['joinTime']))); 
  code>  pre> 
 
 

在这种情况下,我将开始月份添加到数组中,在本例中为May ...现在是什么我 我喜欢这样做是因为几个月过去了,我想把每个新月添加到数组中..所以例如在六月的几天,当六月开始时,我会添加那个月 到了数组..所以我的问题是,如何从开始日期(5月)获得剩余的月份名称。 p>

我需要6月,7月,8月,9月, 10月,11月,12月... p>

如果开始月份是4月,我也会将5月添加到数组中... p>

可以 有人帮我解决这个问题吗? p> div>

First you need to get he month number and than you need to use a loop through to end of the year that is 12. For each month number you also need the month name so use DateTime createFromFormat.

Online Check

$months = array();
$num = date("n",strtotime($me['joinTime']));
array_push($months, date("F", strtotime('2016-05-17 16:41:51')));

for($i = ($num + 1); $i <= 12; $i++){
    $dateObj = DateTime::createFromFormat('!m', $i);
    array_push($months, $dateObj->format('F'));
}

print_r($months); // Array ( [0] => May [1] => June [2] => July [3] => August [4] => September [5] => October [6] => November [7] => December )

Yo can also put it like

$array = array();
array_push($array, date('F')) ;
for ($i=1; $i<=  12 - date('m'); $i++ ){
    array_push($array, date('F', strtotime("+$i months"))) ;
}
print "<pre>";print_r($array);

Here we will be using DatePeriod which allows iteration over a set of dates and times, recurring at regular intervals, over a given period.

So we got the end date and we have the start date and then calculated the interval. And then looping over the period we got the array of months.

// current date : 20 Feb 2019

$startDate = new \DateTime('first day of next month');
$endDate = new \DateTime('1st january next year');

$interval = new \DateInterval('P1M');

$period = new \DatePeriod($startDate, $interval, $endDate);

// Start array with current date
$dates = [];

// Add all remaining dates to array
foreach ($period as $date) {
     array_push($dates, $date->Format('F'));
}

// output
print_r($dates); die;

Array ( [0] => March [1] => April [2] => May [3] => June [4] => July [5] => August [6] => September [7] => October [8] => November [9] => December )