如何确定日期是否在 PHP 中的两个日期之间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6219837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:41:06  来源:igfitidea点击:

How can I determine if a date is between two dates in PHP?

phpdate

提问by celsowm

I need know if a $paymentDate(31/12/2010) is valid between $contractDateBegin(01/01/2001) and $contractDateEnd(01/01/2012)

我需要知道$paymentDate(31/12/2010) 在$contractDateBegin(01/01/2001) 和$contractDateEnd(01/01/2012)之间是否有效

dd/mm/yyyy FORMAT !

dd/mm/yyyy 格式!

回答by Matthew

As of PHP 5.3:

从 PHP 5.3 开始:

$paymentDate = DateTime::createFromFormat('d/m/Y', '31/12/2010');
$contractDateBegin = DateTime::createFromFormat('d/m/Y', '01/01/2001');
$contractDateEnd = DateTime::createFromFormat('d/m/Y', '01/01/2012');

if ($paymentDate >= $contractDateBegin && $paymentDate <= $contractDateEnd)
{
  echo "is between\n";
}

You may need to adjust the use of <=to <depending on whether or not the dates are exclusive.

您可能需要使用调整<=<根据日期是否是排他性的。

回答by jberg

if they are formatted as YYYYMMDD you can check if $paymentDate > $contractDateBegin and $paymentDate < $contractDateEnd

如果它们的格式为 YYYYMMDD,您可以检查是否 $paymentDate > $contractDateBegin and $paymentDate < $contractDateEnd

This works with any numeric format that has the larger formats first. If you have american dates for example MM/DD/YYYY, it doesn't work.

这适用于首先具有较大格式的任何数字格式。如果您有美国日期,例如 MM/DD/YYYY,则它不起作用。

回答by patapizza

$test = strtotime($paymentDate);
if ($test >= strtotime($contractDateBegin) && $test <= strtotime($contractDateEnd))