0

Basically am trying to set a time and a date in PHP then set a time gap which will range between minutes, loop through between a start time and end time echoing something out for each one. Have tried loads of different ways and cant seem to figure a way to set a date and add to it.

This seems the best script I have modified so far:

$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
$newendtime = $endtime->format('Y-m-d H:i');

$timedate = new DateTime('2012-01-01 09:00');

while($stamp < $newendtime)
{
$time = new DateTime($timedate);
$time->add(new DateInterval('PT' . $minutes . 'M'));
$timedate = $time->format('Y-m-d H:i');

echo $timedate;
}
0

3 Answers 3

5
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');

//modified the start value to get something _before_ the endtime:
$time = new DateTime('2012-01-01 8:00');
$interval = new DateInterval('PT' . $minutes . 'M');

while($time < $endtime){
   $time->add($interval);
   echo $time->format('Y-m-d H:i');
}
Sign up to request clarification or add additional context in comments.

Comments

1

Do everything in seconds, and use php's time(), date(), and mktime functions.

In UNIX Time, dates are stored as the number of seconds since Jan 1, 1970.

You can render UNIX Timestamps with date().

 $time = time(); // gets current time
 $endtime = mktime(0,0,0, 1, 31, 2012); // set jan 31 @ midnight as end time
 $interval = 60 * 5;  // 300 seconds = 5 minutes
 while($time < $endtime){
     $time += $interval;
     echo date("M jS Y h:i:s a",$time) . "<br>"; // echos time as Jan 17th, 2012 1:04:56 pm
 }

date reference: https://www.php.net/manual/en/function.date.php (includes superb date format reference too)

mktime reference: https://www.php.net/mktime

time() only gets the current time, but just for kicks n' giggles: https://www.php.net/time

And, it's super easy to store in a database!

1 Comment

Did get it working in seconds but become too complicated for me and found it hard setting up dates, thanks though for your time. Probably more useful if I knew more about PHP, am learning as I go along
0

This function will let you add date to your existing datetime. This will also preserves HH:MM:SS

<?php
function add_date($givendate,$day=0,$mth=0,$yr=0) {
      $cd = strtotime($givendate);
      $newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
    date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
    date('d',$cd)+$day, date('Y',$cd)+$yr));
      return $newdate;
              }

?>

Usage:

add_date($date,12,0,0);

where $date is your date.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.