noneJavaScript
noneJavaScript

Reputation: 845

Object array in php with dates

$date1 = "2007-03-24";
$date2 = "2009-06-26";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

$arary_dates = array ();

for ($days=1;$i<=$days;$days++)
{
$array_dates[$days] -> new DateTime(2007,0,$days);
}

I know this code is wrong made, but is the way I can show to you what i want.

I have an initial date and I want to fill an object array dates with every dates since that initial date until final date (using the number of days passed to increment)

How could I do it?

Upvotes: 0

Views: 91

Answers (3)

Brad Bonkoski
Brad Bonkoski

Reputation: 76

store the dates as a timestamp and use that for your caluclations... i.e.

$start = strtotime($date1);
$end = strtotime($date2);

$dayArray = array();
while($start != $end) {
   $start += 60*60*24;  //seconds in a day, you could alter this to multiple by number of days passed in
   $dayArray[] = $start;
}

Then use the date() method to display the timestamps in the format of your choosing.

Upvotes: 1

Touch
Touch

Reputation: 1491

I haven't done something like this before so I am not sure if my code will work. But try to follow the logic.


$start = strtotime("2007-03-24"); //date1
$end = strtotime("2009-06-26"); //date2

$array_date = array();
while ($start != $end) {
    $array_dates[] = date('Y-m-j',$start);
    $oneDay = 60 * 60 * 24;
    $start += $oneDay;
}


Upvotes: 0

John Conde
John Conde

Reputation: 219864

Obviously you will need to modify the start and end times but this will get you started.

$start = new DateTime('first day of this month');
$end = new DateTime('first day of next month');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);

foreach ($period as $dt)
{
    echo $dt->format("l Y-m-d") . PHP_EOL;
}

Upvotes: 3

Related Questions