簡體   English   中英

計算日期是否落在PHP的給定范圍內(即兩周)

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

我需要能夠檢查給定日期是否在范圍內,例如。 兩周。

例如,如果我設置開始日期,即 2013年1月5日(星期三),想要確定目標日期2014年1月1日(也是星期三)是否在開始日期的兩周之內,什么是最好的方法?

我可以想到的一個選擇是循環使用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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM