PHP检查两个日期是否至少相差三个月

时间:2013-11-11 15:19:00

标签: php

在php中如何检查一个日期(以字符串形式给出)是否与另一个日期相差至少三个月(无法找到任何示例):

$date1 = "2013-11-05";
$date2 = "2013-11-19";
//both dates is in form yyyy.mm.dd
differsThreeMonths($date1,$date2) { ???? return $differs; }
differsThreeMonths("2013-11-05","2014-05-02");//true 
differsThreeMonths("2014-01-01","2014-04-01");//true 
differsThreeMonths("2014-01-01","2014-03-31");//false
differsThreeMonths("2013-12-01","2014-01-15");//false
etc

谢谢

3 个答案:

答案 0 :(得分:4)

$datetime1 = new DateTime('2013-07-01 12:00:00');
$datetime2 = new DateTime('2013-11-11 12:00:00');
$interval = $datetime1->diff($datetime2);
if(($interval->m>=3) || ($interval->y > 0))
echo "at least 3 months";
else
echo "Not greater than 3 months";

答案 1 :(得分:2)

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
var_dump($interaval);

http://www.php.net/manual/en/datetime.diff.php

答案 2 :(得分:1)

尝试:

function differsThreeMonths($date_str1, $date_str2) {
    if (strlen($date_str1) > 0 && strlen($date_str2) > 0) {
        $date1 = new DateTime($date_str1);
        $date2 = new DateTime($date_str2);
        $since_start = $date1->diff($date2);
        return (($since_start->y > 0) || ($since_start->m >= 3));
    } else {
        return -1; // ERROR CODE HERE
    }
}