How can I check if the current date/time is past a

2019-01-03 15:03发布

I'm trying to write a script that will check if the current date/time is past the 05/15/2010 at 4PM

How can I use PHP's date() function to perform this check?

6条回答
做个烂人
2楼-- · 2019-01-03 15:43

There's also the DateTime class which implements a function for comparison operators.

// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');

if ( $dtA > $dtB ) {
  echo 'dtA > dtB';
}
else {
  echo 'dtA <= dtB';
}
查看更多
▲ chillily
3楼-- · 2019-01-03 15:47
date_default_timezone_set('Asia/Kolkata');

$curDateTime = date("Y-m-d H:i:s");
$myDate = date("Y-m-d H:i:s", strtotime("2018-06-26 16:15:33"));
if($myDate < $curDateTime){
    echo "active";exit;
}else{
    echo "inactive";exit;
}
查看更多
Viruses.
4楼-- · 2019-01-03 15:48

Check PHP's strtotime-function to convert your set date/time to a timestamp: http://php.net/manual/en/function.strtotime.php

If strtotime can't handle your date/time format correctly ("4:00PM" will probably work but not "at 4PM"), you'll need to use string-functions, e.g. substr to parse/correct your format and retrieve your timestamp through another function, e.g. mktime.

Then compare the resulting timestamp with the current date/time (if ($calulated_timestamp > time()) { /* date in the future */ }) to see whether the set date/time is in the past or the future.

I suggest to read the PHP-doc on date/time-functions and get back here with some of your source-code once you get stuck.

查看更多
孤傲高冷的网名
5楼-- · 2019-01-03 15:51

I had a problem with this date comparing and need some adjust

function getDatetimeNow() {
  $tz_object = new DateTimeZone('Europe/Belgrade');
  $datetime = new DateTime();
  $datetime->setTimezone($tz_object);
  return $datetime->format('Y\-m\-d\ h:i:s');
}

$currentDate = getDatetimeNow();

$dtA = new DateTime($currentDate);
$dtB = new DateTime($date);

if ( $dtA > $dtB ) {
  $active = 0;
  return $active;
}
else {
  $active = 1;
  return $active;
}
查看更多
该账号已被封号
6楼-- · 2019-01-03 15:52

Since PHP >= 5.2.0 you can use the DateTime class as such:

if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
    # current time is greater than 2010-05-15 16:00:00
    # in other words, 2010-05-15 16:00:00 has passed
}

The string passed to the DateTime constructor is parsed according to these rules.


Note that it is also possible to use time and strtotime functions. See original answer.

查看更多
疯言疯语
7楼-- · 2019-01-03 16:02

The dateTime object range is from about 292 billion years in the past to the same in the future. The timestamp function has a limit (starts from 1970 till 2038 if i remember correctly).

查看更多
登录 后发表回答