Jump to content

[SOLVED] Incrementing a DateTime by minute and add to array as string


marky-b

Recommended Posts

Is there a better way to go about doing this:

 

I'm looking to create a array with the elements being every minute from a classStartTime to an classEndTime (stored as strings).

 

here's what i have so far:

 

$dateFormat = "Y-m-d H:i:s";
$now = date($dateFormat);
$today = date("Y-m-d");
$year = date("Y");
$month = date("m");
$date = date("d");

$classStartTime = $today . " 18:00:00";
$classEndTime = $today . " 20:45:00";
$curTime = $classStartTime;
$dt = strtotime($curTime);
$i = 0;

while ( $dt > strtotime($classEndTime) )
{
    $timeArray[i] = $curTime; //add incrementing time string to array
    $dt = strtotime($curTime); //convert incrementing time string to DateTime
    $dt = $dt + 60; //add 1 minute to DateTime (60 seconds)
    $curTime = date($dateFormat,$dt); //convert back to string
    $i++; //increment index
}

 

soo, the page either times out or doesn't even load.

 

i've even converted the loop to "where ( i < 10 )..."  and it does the same as above.

 

is there an easier way to increment a DateTime by minute, convert to a string, and then store in an array?

 

FYI, i'm working with PHP 5.2.9

 

-mark

I slightly cleared your code and fixed missing dollar sign from index inside while loop. This should work.

 

<?php
$today = date("Y-m-d");
$startTime = $today . " 18:00:00";
$endTime = $today . " 20:45:00";
$dt = strtotime($startTime);
$i = 0;

while ($dt < strtotime($endTime))
{
    $timeArray[$i] = date($dateFormat,$dt);
    $dt = $dt + 60;
    $i++;
}

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

I know the topic is marked as solved, but since you're using PHP 5.2.9 you could also be making good use of the DateTime class (available as of 5.2.0).  For example:

 

$tz   = new DateTimeZone('UTC');
$date = new DateTime('18:00:00', $tz);
$end  = new DateTime('20:45:00', $tz);

$times = array();
while ($date->format('U') <= $end->format('U'))
{
$times[] = $date->format('H:i');
$date->modify('+1 minute');
}

print_r($times);

 

Aside:

Some classes were introduced in PHP 5.3 to work with periods and intervals of time (DatePeriod and DateInterval respectively) but since you're not using that version, the above code snippet will suffice.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.