我正在尝试使用DateTime类来查找一些日期。我使用DateTime :: modify命令查找下周二,它可以工作。但如果我试着在下周二找到另一个时间,我总会得到相同的日期。我做错了什么?
以下是代码:
$date = DateTime::createFromFormat('Y-m-d', '2015-04-01');
echo $date->format('d/m/Y') . "\n";
for ($n = 0; $n < 10; $n++) {
$date = $date->modify("first Tuesday of +1 week");
echo $date->format('d/m/Y') . "\n";
}
这是输出:
01/04/2015
14/04/2015
14/04/2015
14/04/2015
14/04/2015
14/04/2015
14/04/2015
14/04/2015
14/04/2015
14/04/2015
14/04/2015
答案 0 :(得分:2)
在没有+1周的情况下使用“下周二”:
$date = DateTime::createFromFormat('Y-m-d', '2015-04-01');
echo $date->format('d/m/Y') . "\n";
for ($n = 0; $n < 10; $n++) {
$date->modify("next Tuesday");
echo $date->format('d/m/Y') . "\n";
}
输出:
01/04/2015
07/04/2015
14/04/2015
21/04/2015
28/04/2015
05/05/2015
12/05/2015
19/05/2015
26/05/2015
02/06/2015
09/06/2015
顺便说一句,您不需要将modify()
的结果分配给变量,因为它实际修改了对象而不是返回修改日期。
答案 1 :(得分:1)
请尝试动态传递周数,
$date = DateTime::createFromFormat('Y-m-d', '2015-04-01');
echo $date->format('d/m/Y') . "\n";
for ($n = 0; $n < 10; $n++) {
$date = $date->modify("first Tuesday of +".$n." week");
echo $date->format('d/m/Y') . "\n";
}