如何在php中检查两个日期变量之间的时间?
P粉831310404
2023-08-16 13:21:21
[PHP讨论组]
<p>我有3个变量,分别是3个数字(day,year,month)。
它们合在一起成为一个日期类型的变量。
另外,我还有一个日期变量,表示当前日期。</p>
<p>我该如何检查第一个日期是否在当前日期之前13年或更早?
以下是我的代码:</p>
<pre class="brush:php;toolbar:false;">$usersday = (int)$_POST['day'];
$usersyear = (int)$_POST['year'];
$usersmonth = (int)$_POST['month'];
$takedate = date_create("$usersyear-$usersmonth-$usersday");
$date = date_format($takedate, 'd-m-Y');
$currentDate = date('Y-m-d');</pre>
<p><br /></p>
date_*()函数和date()是两个不同的日期库API的一部分,令人困惑的是。面向对象版本的date_*()函数在一定程度上澄清了这一点,同时也是一个更强大的库。例如:$usersyear = 2001; $usersmonth = 1; $usersday = 1; $takedate = new DateTime("$usersyear-$usersmonth-$usersday"); $today = new DateTime('today'); $diff = $today->diff($takedate); var_dump($diff, $diff->y);输出:
object(DateInterval)#3 (10) { ["y"]=> int(22) ["m"]=> int(7) ["d"]=> int(15) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["f"]=> float(0) ["invert"]=> int(1) ["days"]=> int(8262) ["from_string"]=> bool(false) } int(22)参考:https://www.php.net/manual/en/book.datetime.php