简体   繁体   English

PHP日期比较

[英]PHP date comparison

我如何检查“2008-02-16 12:59:57”格式的日期是否少于24小时?

if (strtotime("2008-02-16 12:59:57") >= time() - 24 * 60 * 60)
{ /*LESS*/ }

Just adding another answer, using strtotime 's relative dates: 只需添加另一个答案,使用strtotime的相对日期:

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

I think this makes the code much more readable. 我认为这使代码更具可读性。

if ((time() - strtotime("2008-02-16 12:59:57")) < 24*60*60) {
  // less than 24 hours ago
}

eg via strtotime and time(). 例如通过strtotime和time()。
The difference must be less then 86400 (seconds per day). 差异必须小于86400(每天秒数)。

<?php
echo 'now: ', date('Y-m-d H:i:s'), "\n";
foreach( array('2008-02-16 12:59:57', '2009-12-02 13:00:00', '2009-12-02 20:00:00') as $input ) {
  $diff = time()-strtotime($input);
  echo $input, ' ', $diff, " ", $diff < 86400 ? '+':'-', "\n";
}

prints 版画

now: 2009-12-03 18:02:29
2008-02-16 12:59:57 56696552 -
2009-12-02 13:00:00 104549 -
2009-12-02 20:00:00 79349 +

only the last test date/time lays less than 24 hours in the past. 只有最后一次测试日期/时间过去不到24小时。

Php has a comparison function between two date/time objects , but I don't really like it very much. Php 在两个日期/时间对象之间比较功能 ,但我并不是非常喜欢它。 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(). 我所做的是使用strtotime()从日期对象中生成一个unix时间戳,然后将其与time()的输出进行比较。

Just use it..... 只是用它.....

if(strtotime($date_start) >= strtotime($currentDate))
{
// Your code
}

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";
}

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!";
}

You can use Simple PHP to do this: 您可以使用Simple PHP执行此操作:

$date = new simpleDate();
echo $date->now()->subtractHour(24)->compare('2008-02-16 12:59:57')->isBefore();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM