我正在尝试调用一个函数,该函数将返回从现在到过去可变天数的所有日期。下面是一些与实际代码混合的伪代码。你们可以帮帮忙,以便它能回归所有日子吗?
function getTimeStamps($numDays){
$today = date("Y-m-d");
$startDate = $today - $numdays;
$movingDay = $startDate;
$results = array();
while($movingDay <= $today){
array_push($results,$movingDay);
$movingDay + 1 day;
}
return $results;
}
$dateList = getTimeStamps(8);
此功能将返回
array(
'2013-12-10',
'2013-12-11',
'2013-12-12',
'2013-12-13',
'2013-12-14',
'2013-12-15',
'2013-12-16',
'2013-12-17'
);
答案 0 :(得分:6)
这应该可以解决你所需要的问题。您可以修改它以适合您的确切目的。
$start = new DateTime('2013-12-01');
$end = new DateTime('2013-12-17');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt)
{
echo $dt->format("Y-m-d") . PHP_EOL;
}
答案 1 :(得分:1)
function getTimeStamps($numDays){
$dates = array();
for ($i=$numDays-1; $i>=0; $i--){
$dates[] = date("Y-m-d", strtotime("now - $i days"));
}
return $dates;
}
因此...
print_r(getTimeStamps(8));
打印出来:
Array
(
[0] => 2013-12-10
[1] => 2013-12-11
[2] => 2013-12-12
[3] => 2013-12-13
[4] => 2013-12-14
[5] => 2013-12-15
[6] => 2013-12-16
[7] => 2013-12-17
)
答案 2 :(得分:1)
约翰的答案很棒;作为补充,这是一个使用更老式的时间戳的示例,包含在生成器中:
function getPastDates($daysAgo)
{
$current = strtotime(sprintf('-%d days', $daysAgo));
for ($i = 0; $i < $daysAgo; ++$i) {
yield $current;
$current = strtotime('+1 day', $current);
}
}
foreach (getPastDates(7) as $ts) {
echo date('Y-m-d', $ts), "\n";
}
答案 3 :(得分:0)
此函数将返回填充了DateTime
个对象的数组,从今天到今天+ X天:
function getTimeStamps($numDays) {
$now = new DateTime('today');
$interval = new DateInterval('P1D');
$periods = new DatePeriod($now, $interval, $numDays-1);
return iterator_to_array($periods);
}
如果您希望以不同方式格式化日期,只需循环它们:
$datesBefore = getTimeStamps(4);
$datesAfter = array_map(function($dt) { return $dt->format('Y-m-d'); }, $datesBefore);
的 demo 强>