PHP 检查日期是否超过了以特定格式给出的特定日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19031235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Check if date is past to a certain date given in a certain format
提问by Satch3000
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?
我怎样才能做到这一点?
回答by Amal Murali
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.
注意:使用DateTime
class 是首选,strtotime()
因为后者仅适用于 2038 年之前的日期。阅读有关Year_2038_problem 的更多信息。
回答by newfurniturey
You can use strtotime()
and time()
:
您可以使用strtotime()
和time()
:
if (strtotime($event['date']) < time()) {
// past date
}
回答by Menon Jats
@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';
}
回答by C Travel
if (time() > strtotime($event['date']))
{
// current date is greater than 2013-07-31
}
strtotimeparses the date sting using these rules.