我有以下几点
$var = "2010-01-21 00:00:00.0"
我想将这个日期与今天的日期进行比较(即我想知道这个$var是否在今天之前或等于今天)
我需要使用什么函数?
我有以下几点
$var = "2010-01-21 00:00:00.0"
我想将这个日期与今天的日期进行比较(即我想知道这个$var是否在今天之前或等于今天)
我需要使用什么函数?
当前回答
$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');
var_dump(strtotime($today) > strtotime($expiry)); //false or true
其他回答
strtotime($var);
将其转换为时间值
time() - strtotime($var);
给出自$var后的秒数
if((time()-(60*60*24)) < strtotime($var))
将检查$var是否在最后一天内。
给你:
function isToday($time) // midnight second
{
return (strtotime($time) === strtotime('today'));
}
isToday('2010-01-22 00:00:00.0'); // true
另外,还有一些帮助函数:
function isPast($time)
{
return (strtotime($time) < time());
}
function isFuture($time)
{
return (strtotime($time) > time());
}
这种格式非常适合于标准字符串比较。
if ($date1 > $date2){
//Action
}
要以这种格式获取今天的日期,只需使用:date("Y-m-d H:i:s")。
So:
$today = date("Y-m-d H:i:s");
$date = "2010-01-21 00:00:00";
if ($date < $today) {}
这就是这种格式的美妙之处:它很好地排序。当然,这可能会降低效率,这取决于您的具体情况,但它也可能更方便,并导致更可维护的代码-我们需要了解更多才能真正做出判断。
对于正确的时区,您可以使用,例如,
date_default_timezone_set('America/New_York');
点击这里查看可用的PHP时区。
$toBeComparedDate = '2014-08-12';
$today = (new DateTime())->format('Y-m-d'); //use format whatever you are using
$expiry = (new DateTime($toBeComparedDate))->format('Y-m-d');
var_dump(strtotime($today) > strtotime($expiry)); //false or true
一些给出的答案没有考虑到今天!
这是我的建议。
$var = "2010-01-21 00:00:00.0"
$given_date = new \DateTime($var);
if ($given_date == new \DateTime('today')) {
//today
}
if ($given_date < new \DateTime('today')) {
//past
}
if ($given_date > new \DateTime('today')) {
//future
}