发布日期在1个月前,使用PHP的日期

问题描述 投票:0回答:2

我正在编写一个检查给定日期是否在1个月之前的代码,因为我的代码在下面给出

$date = ('2020-02-04');
$myDate = date("Y-m-d", strtotime( date( "Y-m-d", strtotime( date("Y-m-d") ) ) . "-1 month" ) );
if (strtotime($date) < $myDate) {
   echo "Time is beyond 3 months";
}else{
   echo "Time is not  beyond 3 months";
}

但是这行不通,有人可以帮我吗

php
2个回答
0
投票

$ myDate分配逻辑以及if语句都有一些问题,对于动态日期,您可以使用下面的代码:

<?php
$date = ('2020-02-04');
$myDate = date("Y-m-d", strtotime("-1 month", strtotime($date)));
if (strtotime($date) < strtotime($myDate)) {
   echo "Time is beyond 3 months";
}else{
   echo "Time is not  beyond 3 months";
}

Check output here


0
投票

您需要使用datetime()来更正您的代码:

$date = '2020-01-04';

$myDate = date('Y-m-d', strtotime('-1 month'));

$date1 = new DateTime($myDate);
$date2 = new DateTime($date);
$interval = $date1->diff($date2);

echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

if($interval->m >3){
    echo "Time is beyond 3 months";
}else{
    echo "Time is not  beyond 3 months";
}

输出:https://3v4l.org/vTTK8

© www.soinside.com 2019 - 2024. All rights reserved.