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
What would be the best way 开发者_开发知识库of doing this? I may want to generate up to 1000 lines like this
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.
I would suggest checking out PHP's built-in functions: date
and mktime
.
Used together you can achieve what you want.
As an example to increment the day taken directly from the website.
<?php
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
?>
<?PHP
for ( $i = 0; $i < 1000; $i++ ) {
$startTimeSec = mktime(11, 30 + $i, 0, 2, 12, 2010);
echo date("Y, m, d, h, i", $startTimeSec) . "\n" . '<br />';
}
?>
for($i=1;$i<=10;$i++){
$tomorrow = mktime(0,0,0,date("m"),date("d")+$i,date("Y"));
echo "Tomorrow is ".date("Y m d", $tomorrow);
}
Simplest that comes to my mind with PHP < 5.3
echo '(year, month, day, hour, minute)', PHP_EOL;
for($i = 0; $i < 1000; $i++) {
echo date('Y, m, d, H, i', strtotime("+$i minute")), PHP_EOL;
}
精彩评论