[英]PHP Check if date is past to a certain date given in a certain format
I have a php event's calender which queries the database to get the dates. 我有一个php事件的日历,它查询数据库以获取日期。
I display the event date using: 我使用以下方式显示活动日期:
$event['date']
and this display's in this format: 该显示的格式如下:
2013-07-31
for example. 例如
2013-07-31
。
Now, what I need to do is to check if this date is a past date to the current date. 现在,我需要检查此日期是否是当前日期的过去日期。
How can I do this? 我怎样才能做到这一点?
You can compare the dates with PHP's DateTime
class: 您可以将日期与PHP的
DateTime
类进行比较:
$date = new DateTime($event['date']);
$now = new DateTime();
if($date < $now) {
echo 'date is in the past';
}
Note: Using DateTime
class is preferred over strtotime()
since the latter will only work for dates before 2038. Read more about the Year_2038_problem . 注意:与
strtotime()
首选使用DateTime
类,因为后者仅适用于2038年之前的日期。有关Year_2038_problem的更多信息。
You can use strtotime()
and time()
: 您可以使用
strtotime()
和time()
:
if (strtotime($event['date']) < time()) {
// past date
}
if (time() > strtotime($event['date']))
{
// current date is greater than 2013-07-31
}
strtotime parses the date sting using these rules . strtotime使用这些规则解析日期字符串。
@Satch3000 You've accepted the wrong answer as a right solution ( @Amal Murali ) @ Satch3000您已经接受了错误的答案作为正确的解决方案(@Amal Murali)
Please see the output, Here I input the today date but it returns current date as past date. 请查看输出,在这里输入今天的日期,但它返回当前日期作为过去的日期。
<?php
/* Enter today date */
$date = new DateTime("09/14/2017");
$now = new DateTime();
print_r($date);
print_r($now);
if($date < $now) {
echo 'date is in the past';
}
Output will be 输出将是
DateTime Object
(
[date] => 2017-09-14 00:00:00.000000
[timezone_type] => 3
[timezone] => UTC
)
DateTime Object
(
[date] => 2017-09-14 07:12:52.000000
[timezone_type] => 3
[timezone] => UTC
)
date is in the past
Solution 解
$Date1 = strtotime(date('Y-m-d', strtotime('2017-09-15') ) ).' ';
$Date2 = strtotime(date('Y-m-d'));
if($Date1 < $Date2) {
echo 'date is in the past';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.