PHP date comparison

2019-03-11 07:05发布

How would I check if a date in the format "2008-02-16 12:59:57" is less than 24 hours ago?

标签: php date time
9条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-11 07:20

Php has a comparison function between two date/time objects, but I don't really like it very much. It can be imprecise.

What I do is use strtotime() to make a unix timestamp out of the date object, then compare it with the output of time().

查看更多
我命由我不由天
3楼-- · 2019-03-11 07:26

Just adding another answer, using strtotime's relative dates:

$date = '2008-02-16 12:59:57';
if (strtotime("$date +1 day") <= time()) {
    // Do something
}

I think this makes the code much more readable.

查看更多
来,给爷笑一个
4楼-- · 2019-03-11 07:27
if (strtotime("2008-02-16 12:59:57") >= time() - 24 * 60 * 60)
{ /*LESS*/ }
查看更多
Bombasti
5楼-- · 2019-03-11 07:37

There should be you variable date Like

$date_value = "2013-09-12";
$Current_date = date("Y-m-d"); OR $current_date_time_stamp = time();

You can Compare both date after convert date into time-stamp so :

if(strtotime($current_date) >= strtotime($date_value)) {
 echo "current date is bigger then my date value";
}

OR

if($current_date_time_stamp >= strtotime($date_value)) {
 echo "current date is bigger then my date value";
}
查看更多
Viruses.
6楼-- · 2019-03-11 07:42

Maybe it will be more easy to understand...

$my_date        = '2008-02-16 12:59:57';
$one_day_after  = date('Y-m-d H:i:s', strtotime('2008-02-16 12:59:57 +1 days'));

if($my_date < $one_day_after) {
echo $my_date . " is less than 24 hours ago!";
} else {
echo $my_date . " is more than 24 hours ago!";
}
查看更多
唯我独甜
7楼-- · 2019-03-11 07:45
if ((time() - strtotime("2008-02-16 12:59:57")) < 24*60*60) {
  // less than 24 hours ago
}
查看更多
登录 后发表回答