tizmantiz
tizmantiz

Reputation: 23

check if new DateTime is today or future in php

I need to check if date1 is today or future date and if so its ok if not (is in the past) its not ok. i see a lot of examples but none of theme is check if date1 is equal today. my code is:

$today = new DateTime(); // Today
$today->format('Y-m-d'); //2016-10-27
$contractDateBegin = new DateTime($date1); //2016-10-27

if($today->getTimestamp() <= $contractDateBegin->getTimestamp()){
   echo 'OK';
}
else{
   echo "NOT OK";
}

its work fine if date1 is a future date but if its the same date its echo "NOT OK"

any help?

Upvotes: 1

Views: 2549

Answers (4)

simon
simon

Reputation: 2946

I guess you only want to compare the dates (ignoring the time). This should work:

$today = new DateTime();
$today = $today->format('Y-m-d');
$contractDateBegin = new DateTime($date1);
$contractDateBegin = $contractDateBegin->format('Y-m-d');

if ($today <= $contractDateBegin){
    echo 'OK';
} else {
   echo "NOT OK";
}

Upvotes: 0

Manh Nguyen
Manh Nguyen

Reputation: 940

$today can be defined as just new DateTime("today"), which means today at midnight -- the time part will be automatically zeroed out

$today = new DateTime("today"); 
$date1 = '2016-10-27';
$contractDateBegin = new DateTime($date1); //2016-10-27
if($today <= $contractDateBegin){
    echo 'OK';
}
else{
    echo "NOT OK";
}

DEMO

Upvotes: 1

Tam Nguyen
Tam Nguyen

Reputation: 84

getTimestamp() included "H:i:s". So it'll fail when compare the seconds. In your case, do you want to compare just date('Y-m-d')? If you just want to use DateTime and compare Timestamp. Please try

$today = new DateTime(); // Today
$contractDateBegin = new DateTime($date1); //2016-10-27

// Set time to 0
$today->setTime(0, 0, 0);
$contractDateBegin->setTime(0, 0, 0);

if($today->getTimestamp() <= $contractDateBegin->getTimestamp()){
   echo 'OK';
}
else{
   echo "NOT OK";
}

Upvotes: 0

jakub wrona
jakub wrona

Reputation: 2254

The "Y-m-d format" is perfect also for direct lexicographical comparison of strings and there is no need to convert it to a DateTime object. With PHP7 you could use the famous speceship operator ;)

php -a
Interactive mode enabled

php > $today = '2016-10-27';
php > $tomorrow = '2016-10-28';
php > $today2 = '2016-10-27';

php > echo $today <=> $tomorrow;
-1
php > echo $today <=> $today2;
0
php > echo $tomorrow <=> $today2;
1

Upvotes: 0

Related Questions