[英]Get all dates between now and x days from now
我試圖調用一個函數,它將返回從現在到過去可變天數的所有日子。 下面是一些與實際代碼混合的偽代碼。 你們可以幫忙,這樣它會回歸所有日子嗎?
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'
);
這應該是你需要的繁重工作。 您可以修改它以適合您的確切目的。
$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;
}
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
)
約翰的答案很棒; 作為補充,這是一個使用包含在生成器中的更老式時間戳的示例:
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";
}
此函數將返回填充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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.