PHP 比较日期时间值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4989410/
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 Compare datetime values
提问by dtntcdr
In my PHP application I'm trying to compare date time values like the following:
在我的 PHP 应用程序中,我试图比较日期时间值,如下所示:
if($datetime_from_db < date('Y-m-d H:i:s'))
{
// then do something
}
Both values are in the same format. What I can't figure out is why it only compares the date and ignores the time. Both the date and the time values are important for me but I don't know how to make it work.
两个值的格式相同。我想不通的是为什么它只比较日期而忽略时间。日期和时间值对我都很重要,但我不知道如何使它起作用。
回答by deceze
Comparing a stringlike "2011-02-14 15:46:00"
to another stringdoesn't actually compare dates, it compares two strings according string parsing numeric rules. You will need to compare actual numeric timestamps:
将一个字符串与"2011-02-14 15:46:00"
另一个字符串进行比较实际上并不比较日期,而是根据字符串解析数字规则比较两个字符串。您需要比较实际的数字时间戳:
strtotime($datetime_from_db) < time()
回答by Andrew
If you want this to work with dates past 2038, you can't use strtotime() or time().
如果您希望它处理 2038 年以后的日期,则不能使用 strtotime() 或 time()。
See this questionfor the explanation.
请参阅此问题以获取解释。
A better approach:
一个更好的方法:
new DateTime($datetime_from_db) < new DateTime();
new DateTime($datetime_from_db) < new DateTime();
回答by Tarun Gupta
This may help you.
这可能对你有帮助。
$today = date("m-d-Y H:i:s");
$thisMonth =date("m");
$thisYear = date("y");
$expectedDate = $thisMonth."-08-$thisYear 23:58:00";
//pr($today);
//pr($expectedDate);
if (strtotime($expectedDate) > strtotime($today)) {
echo "Expected date is greater then current date";
return ;
} else
{
echo "Expected date is lesser then current date";
}