计算日期是否在给定范围内(例如:在PHP中


Calculating if date falls within a given range (ie. fortnights) in PHP

我需要能够检查一个给定的日期是否落在一个范围内,例如。两周。

例如,如果我设置一个开始日期,即:01/05/2013(这是一个星期三),并且想知道目标日期01/01/2014(也是一个星期三)是否在开始日期的两周范围内,最好的方法是什么?

我可以想到的一个选项是使用strtotime()循环,直到我达到或超过目标日期,但我想知道是否有更好更有效的方法来做到这一点。最好是我可以在其他范围内使用的东西,例如。季度等等. .

谢谢你的帮助。

使用

if ( ( strtotime($targetdate) - strtotime($startdate) ) <= (14 * 24 * 60 * 60) )

如果你想要季度,那么它就变成

if ( ( strtotime($targetdate) - strtotime($startdate) ) <= (3 * 30 * 24 * 60 * 60) )

关于strtotime你是对的,但我不明白你为什么要循环。你可以这样写:

$fortnight = 14 * 86400; // Fortnight in seconds.
$start = strtotime("01/05/2013");
$check = strtotime("01/01/2014");
// Check if the date is within a fortnight of start date
if ($start > $check && $start - $check <= $fortnight) {
  // Check date is within a fortnight before start date.
}
else if ($start < $check && $check - $start <= $fortnight) {
  // Check date is within a fortnight after start date.
}
相关文章: