php 创建阵列时间表从00:00 - 23:55为每5分钟

xiozqbni  于 2023-03-11  发布在  PHP
关注(0)|答案(5)|浏览(200)

我想创建一个包含从00:00到23:55的所有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 00:00');
$interval = new DateInterval('PT' . $minutes . 'M');

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

我如何改变这一点,使输出可以与json一起使用?
例如:

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

我的问题不在于创建JSON,而在于创建一个没有日期部分的小时/分钟列表。

2w3kk1z5

2w3kk1z51#

你几乎都在那里,只是一个小星期,正如泰耶建议使用H:i。也许这样的东西:

$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);
4urapxun

4urapxun2#

DateTime::format的参数控制字段的选择,如下所示:

  • Y:年份
  • m:月份
  • d:日
  • H:小时
  • i:分钟

仅获取小时和分钟:使用'H:i'作为格式字符串。
有关更多格式选项:参见http://www.php.net/manual/en/function.date.php
如果您不能使用DateTime函数,我将生成如下数组:

$times = array();
for ($h = 0; $h < 24; $h++){
  for ($m = 0; $m < 60 ; $m += 5){
    $time = sprintf('%02d:%02d', $h, $m);
    $times["'$time'"] = "'$time'";
  }
 }
gk7wooem

gk7wooem3#

试试看:

echo json_encode($Var);

这应该做的伎俩..查看手册在这里:http://www.php.net/manual/en/function.json-encode.php

toe95027

toe950274#

4.我知道现在很晚了,但下面的方法可能对某人有帮助

$step = 5;
$periods = new DatePeriod(
    new DateTime("2021-01-01 00:00:00"),
    new DateInterval('PT' . $step . 'M'),
    new DateTime("2021-01-01 23:59:00")
);

foreach($periods as $d){
    echo $d->format("H:i");
}
nzrxty8p

nzrxty8p5#

必须先更新我的php版本才能使用这些DateTime类:(所以现在我只是把它写出来,并使用15分钟的间隔,如:

function json_select_starttijd_ronde()
{
$jsonStarttijd_ronde = array();

$jsonStarttijd_ronde['00:00'] = '00:00';
$jsonStarttijd_ronde['00:15'] = '00:15';
    // etcetera

$jsonStarttijd_ronde['23:45'] = '23:45';

return $jsonStarttijd_ronde;

}

相关问题