我有一个函数,它返回一个日期数组。从现在到去年,我需要每七天跳一次。
$date[] = $lastDate = (new \DateTIme('NOW'))->format('Y-m-d');
for ($i = 1; $i < 54; ++$i) { // 54 -> number of weeks in a year
$date[] = $lastDate = date('Y-m-d', strtotime('-7 day', strtotime($lastDate)));
}
return array_reverse($date);
很管用,但我可以做得更好。我想改变它,因为一年中使用54的周数不是很好。(它可以改变)
所以我想使用DateInterval
php类。我可以知道去年的日期:
$lastYear = date('Y-m-d', strtotime('-1 year', strtotime($lastDate)));
但是,我不知道如何使用DateInterval
类拥有我所有的日期数组。
有人能帮我吗?我对日期操纵很不在行。
下面是一个关于我需要什么的示例数组:
["2015-07-06", "2015-07-13", "2015-07-20", "2015-07-27", "2015-08-03", "2015-08-10", "2015-08-17", "2015-08-24", "2015-08-31", "2015-09-07", "2015-09-14", "2015-09-21", "2015-09-28", "2015-10-05", "2015-10-12", "2015-10-19", "2015-10-26", "2015-11-02", "2015-11-09", "2015-11-16", "2015-11-23", "2015-11-30", "2015-12-07", "2015-12-14", "2015-12-21", "2015-12-28", "2016-01-04", "2016-01-11", "2016-01-18", "2016-01-25", "2016-02-01", "2016-02-08", "2016-02-15", "2016-02-22", "2016-02-29", "2016-03-07", "2016-03-14", "2016-03-21", "2016-03-28", "2016-04-04", "2016-04-11", "2016-04-18", "2016-04-25", "2016-05-02", "2016-05-09", "2016-05-16", "2016-05-23", "2016-05-30", "2016-06-06", "2016-06-13", "2016-06-20", "2016-06-27", "2016-07-04"]
发布于 2016-08-16 12:06:41
PHP获得了它自己的原生DateInterval对象。下面是一个简短的示例,如何使用它。
$oPeriodStart = new DateTime();
$oPeriodEnd = new DateTime('+12 months');
$oPeriod = new DatePeriod(
$oPeriodStart,
DateInterval::createFromDateString('7 days'),
$oPeriodEnd
);
foreach ($oPeriod as $oInterval) {
var_dump($oInterval->format('Y-m-d));
}
那么我们在这里做了些什么呢?对于一段时间的日期,你需要一个开始日期、一个结束日期和间隔。你自己测试一下。玩得开心。
发布于 2016-08-16 10:07:37
试试这个:
$timestamp = strtotime("last Sunday");
$sundays = array();
$last_year_timestamp = strtotime("-1 year ",$timestamp);
while($timestamp >= $last_year_timestamp) {
if (date("w", $timestamp) == 0) {
$sundays[] = date("Y-m-d", $timestamp);
$timestamp -= 86400*7;
continue;
}
$timestamp -= 86400;
}
https://stackoverflow.com/questions/38971802
复制相似问题