简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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