Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create array timelist from 00:00 - 23:55 for every 5 minutes

Tags:

php

datetime

time

I want to create an array with all the 5 minute times from 00:00 to 23:55

On this forum I found:

$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 00:00');
$interval = new DateInterval('PT' . $minutes . 'M');

while($time < $endtime){
    $time->add($interval);
echo $time->format('Y-m-d H:i');
}

How do I change this so that the output can be used with json?

For example:-

$aArray = {"00:00":"00:00","00:05":"00:05", ......"23:55":"23:55"}

My problem is not in creating json, but in creating an hour/minute list without the date part.

like image 813
Terradon Avatar asked Apr 08 '13 18:04

Terradon


3 Answers

You are allmost there, just little tweek and as Terje suggest using H:i. Perhaps something like this:

$startTime  = new \DateTime('2010-01-01 00:00');
$endTime    = new \DateTime('2010-01-01 23:55');
$timeStep   = 5;
$timeArray  = array();

while($startTime <= $endTime)
{
    $timeArray[] = $startTime->format('H:i');
    $startTime->add(new \DateInterval('PT'.$timeStep.'M'));
}

echo json_encode($timeArray);
like image 84
Oli Avatar answered Oct 22 '22 14:10

Oli


The argument to DateTime::format controlls the selection of fields like this:

  • Y: year
  • m: month
  • d: day
  • H: hour
  • i: minute

To get only hour and minute: Use 'H:i' as format string.

For more formatting options: See http://www.php.net/manual/en/function.date.php

And if you can't use the DateTime functions, I would have generated the array like this:

$times = array();
for ($h = 0; $h < 24; $h++){
  for ($m = 0; $m < 60 ; $m += 5){
    $time = sprintf('%02d:%02d', $h, $m);
    $times["'$time'"] = "'$time'";
  }
 }
like image 37
Terje D. Avatar answered Oct 22 '22 14:10

Terje D.


Try:

echo json_encode($Var);

This should do the trick.. View the manual here: http://www.php.net/manual/en/function.json-encode.php

like image 1
Daryl Gill Avatar answered Oct 22 '22 14:10

Daryl Gill