Only future dates with PHP strtotime()
PHP的strtotime()默认使用当前年份。如何仅获取将来的日期?
我无法设法获得4月的下一个第一个星期日。日期不能是过去的日期,并且必须始终是相对的(没有硬编码的2017或2018)。
1 2 3 |
我想我可以分多个步骤进行操作,也可以创建一个函数来检查当前时间是否在第一个星期日之前/之后,并在末尾插入"下一年"。
但是我想知道strtotime()是否有一个简单的解决方案
我认为这不是特别优雅,但是它可以正常工作,希望它是您想要的吗?
但是,这似乎是一个更好,可维护且易读的解决方案
1 2 3 4 5 | $d = new DateTime(); $d->modify( 'first day of next year'); echo $d->format('l d. M Y') . PHP_EOL; $d->modify( 'first sunday of april'); echo $d->format('l d. M Y') . PHP_EOL; |
哪个给出
1 2 | Tuesday 01. Aug 2017 Sunday 02. Apr 2017 |
年份更改日期的回声,您无需做,它只是用来证明年份更改了
这是一个更强大的解决方案。它替换了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?php function strtotimeForce($string, $direction) { $periods = array("day","week","month","year"); if($direction !="past" && $direction !="future") return strtotime($string); else if($direction =="past" && strtotime($string) <= strtotime("now")) return strtotime($string); else if($direction =="future" && strtotime($string) >= strtotime("now")) return strtotime($string); else if($direction =="past" && strtotime($string) > strtotime("now")) { foreach($periods as $period) { if(strtotime($string) < strtotime("+1 $period") && strtotime($string, strtotime("-1 $period"))) { return strtotime($string, strtotime("-1 $period")); } } return strtotime($string); } else if($direction =="future" && strtotime($string) < strtotime("now")) { foreach($periods as $period) { if(strtotime($string) > strtotime("-1 $period") && strtotime($string, strtotime("+1 $period")) > strtotime("now")) { return strtotime($string, strtotime("+1 $period")); } } return strtotime($string); } else return strtotime($string); } |
我是来这里寻找帖子标题的解决方案的。我想每次获取strtotime结果的未来日期。
如果今天的日期是2018年1月1日,它将返回未来的日期2018-01-02,但是如果今天的日期是2018年1月3日,它将返回相同的日期(现在是过去的日期)。在这种情况下,我宁愿找回2019年1月2日。
我知道OP表示他们不想要功能,但这似乎是最简单的解决方案。因此,这是我获得的下一个将来匹配的strtotime的快速功能。
1 2 3 |
使用...获得美好的date...
1 |