PHP 日期比较早于 15 天


PHP date compare older than 15 days

我花了很长时间来设定一个特定的日期,但我没有得到正确的表达。我想从用户那里获取日期,并将该日期与比今天早 15 天的日期进行比较。如果它超过 15 天,则转换为今天,否则打印它是什么。

$todaydate= $_GET['date'];// getting date as 201013 ddmmyy submitted by user
$todaydate=preg_replace("/[^0-9,.]/", "", $todaydate); 
$today =date("dmy"); //today ddmmyy
$older= date("dmy",strtotime("-15 day")); // before 15 days 051013
if ($todaydate <= $older){
$todaydate= $today;}

问题是,它以日期作为数字并给出错误的结果。

比较日期字符串有点笨拙,容易失败。尝试比较实际日期对象

$userDate = DateTime::createFromFormat('dmy', $_GET['date']);
if ($userDate === false) {
    throw new InvalidArgumentException('Invalid date string');
}
$cmp = new DateTime('15 days ago');
if ($userDate <= $cmp) {
    $userDate = new DateTime();
}

此外,strtotime有一些严重的限制(请参阅 http://php.net/manual/function.strtotime.php#refsect1-function.strtotime-notesand),在非美国区域设置中没有用。DateTime类更加灵活和最新。

试试这个:

<?php
$todaydate = date(d-m-Y,strtotime($_GET['date']));
$today = date("d-m-Y");
$older= date("d-m-Y",strtotime("-15 day"));
if (strtotime($todaydate) <= strtotime($older)) 
{
$todaydate= $today;
}
?>
$previousDate = "2012-09-30";
if (strtotime($previousDate) <= strtotime("-15 days")) {
    //the date in $previousDate is earlier or is equal to the date 15 days before from today
}