简体   繁体   English

计算日期是否落在PHP的给定范围内(即两周)

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

I need to be able to check if a given date falls within a range, eg. 我需要能够检查给定日期是否在范围内,例如。 fortnights. 两周。

For example, if I set a start date, ie. 例如,如果我设置开始日期,即 01/05/2013 (which is a Wednesday) and wants to find out if the target date, 01/01/2014 (also a Wednesday) falls within fortnight range from the start date, what is the best way to do this. 2013年1月5日(星期三),想要确定目标日期2014年1月1日(也是星期三)是否在开始日期的两周之内,什么是最好的方法?

One option I can think is to loop using strtotime() until I get to or past the target date, but was wondering if there is a better and more efficient way to do this. 我可以想到的一个选择是循环使用strtotime()直到我到达或超过目标日期,但是想知道是否有更好,更有效的方法来执行此操作。 Preferably something that I can use with other range, eg. 最好是我可以在其他范围内使用的东西,例如。 quarterly, etc.. 季度等。

Thanks for any help. 谢谢你的帮助。

Use 采用

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

If you want quarterly, then it becomes 如果您想每季度一次,那么它将变为

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

You are right about strtotime but I don't see why you have to loop. 您对strtotime看法是正确的,但我不明白为什么要循环。 You can use something like this: 您可以使用如下形式:

$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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM