Generate incrementing date strings

前端 未结 5 491
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 06:03

I need to generate a string of incrementing dates, something like this:

(year, month, day, hour, minute)
2010, 2, 12, 11, 30
2010, 2, 12, 11, 31
etc
5条回答
  •  离开以前
    2021-01-26 06:51

    You can use the date classes (note: DateInterval and DatePeriod are only available as of PHP 5.3) to make life easy.

    $start    = new DateTime('2010-02-12 11:30', new DateTimeZone('UTC'));
    $interval = new DateInterval('PT1M'); // 1 minute interval
    $period   = new DatePeriod($start, $interval, 100); // Run 100 times
    
    foreach ($period as $datetime) {
        // Output like: 2009, 02, 12, 11, 30
        echo $datetime->format("Y, m, d, H, i") . PHP_EOL;
    }
    

    For a less pretty, but available in older versions of PHP, alternative then see the other suggestions recommending mktime.

提交回复
热议问题