简体   繁体   中英

creating dates+times every 15 minutes does not work

My php code below is supposed to create a list of following dates + times.

// your code goes here
$maxdays = 1;
for($daynumber=0;$daynumber<$maxdays;$daynumber++){
    $currentdayval = "+".(string)($daynumber-$maxdays)." days";
    $minutes=0;
    for($quarter=0;$quarter<24*4;$quarter++){
        $minutes += $quarter*15;
        $currentminutesval = $minutes." minutes";
        $date_sql = date("Y-m-d H:i:s",strtotime($currentdayval." + ".$currentminutesval)); //current date
        echo $date_sql. "\n";
    }//for $quarter

}//for $daynr

But the output below shows that not every date/time follows 15 minutes after the previous date/time. Not sure where my code goes wrong(?)

2014-06-26 12:44:15
2014-06-26 12:59:15
2014-06-26 13:29:15
2014-06-26 14:14:15
2014-06-26 15:14:15
2014-06-26 16:29:15
2014-06-26 17:59:15
2014-06-26 19:44:15
2014-06-26 21:44:15
2014-06-26 23:59:15
2014-06-27 02:29:15
2014-06-27 05:14:15
2014-06-27 08:14:15
2014-06-27 11:29:15

For your code to work, you need $minutes to be 0, then 15, then 30, then 45...

But because you're incrementing, you get $minutes set to 0, then 15... then 45 (15+30), then 90 (15+30+45), then 150 (15+30+45+60)...

Try $minutes = $quarter * 15; instead of +=

Here's an alternate way that is much cleaner than your current solution and avoids potential date math issues like you are having:

$start    = new DateTime();
$finish   = new DateTime("+{maxdays} days");
$interval = new DateInterval('PT15M');
$period   = new DatePeriod($start, $interval, $finish);
foreach ($period as $date) {
    printf("%s\n<br>", $date->format('Y-m-d H:i:s'));
}

Demo

It creates your start and end date/time and your interval of 15 minutes. It then use DatePeriod to loop through them and output the date and time for you. All of the date math is done by PHP for you.

Try replacing

$minutes += $quarter*15;

By

$minutes += 15;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM