Dates Associative Array- 2014 to today in months

Hi Guys,

I need help.

how can i generate for each month since 2014 the start date and end date in UTC format?

i am trying to make a table of stats .

so for each month it would do basically similar output to

(‘startdate’ => ‘2014-01-01’,‘enddate’ => ‘2014-01-31’,‘startdate’ => ‘2014-02-01’,‘enddate’ => ‘2014-02-31’)

etc

<?php
$startdate = strtotime( '2014-01-01' );
$enddate = strtotime( '2015-03-31' );
$loopdate = $startdate;
$datesArray = array();
while( $loopdate <= $enddate ) {
   $datesArray[$loopdate] = 0;
   $loopdate = strtotime( '+1 month', $loopdate );
   $startdate = date("m/31/Y",$loopdate);
   $enddate = date("m/01/Y",$loopdate);
 
}

ended up using this code :slight_smile:

Try this:

define('ONE_DAY', 60*60*24);
$startdate  = strtotime( '2014-01-01' );
$enddate    = strtotime( '2015-03-31' );
$loopdate   = $startdate;
$datesArray = array();

$i2=0;
while( $i2<25) {
   $startdate = date("M d Y", $loopdate);
   $nextMonth = strtotime( '+1 month', $loopdate );
   $enddate   = date("M d Y", $nextMonth - ONE_DAY);

   $loopdate  = strtotime( '+1 month', $loopdate );
   $i2++;

   $datesArray[ $startdate ] = $enddate;
}

echo '<pre>'; 
  print_r($datesArray); 
echo '</pre>';  

Output:

Here’s a different way of doing it using DateTime:

<?php
date_default_timezone_set('America/Detroit'); // Set the Default Time Zone:
$dates = array();
function getDates($year="2014") {
	
$startYear = new DateTime('01-01-' . $year);
$endYear = new DateTime("Now");
 while ($startYear->format('Y-m-d') <= $endYear->format('Y-m-d')) {
    $startDate = $startYear->format('Y-m-d');
    $startYear->modify('last day of this month');
    $endDate  = $startYear->format('Y-m-d');
    $dates[$startDate] = $endDate;
    $startYear->modify('first day of next month');
  }
  return $dates;
}

$dates = getDates();

echo '<pre>' . print_r($dates,1) . '</pre>';

the output
Array
(
[2014-01-01] => 2014-01-31
[2014-02-01] => 2014-02-28
[2014-03-01] => 2014-03-31
[2014-04-01] => 2014-04-30
[2014-05-01] => 2014-05-31
[2014-06-01] => 2014-06-30
[2014-07-01] => 2014-07-31
[2014-08-01] => 2014-08-31
[2014-09-01] => 2014-09-30
[2014-10-01] => 2014-10-31
[2014-11-01] => 2014-11-30
[2014-12-01] => 2014-12-31
[2015-01-01] => 2015-01-31
[2015-02-01] => 2015-02-28
[2015-03-01] => 2015-03-31
)

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.