gadss
gadss

Reputation: 22489

PHP Comparison between dates

I have this code:

$val_datefrom = strtotime("2015-01-01");
$val_datefrom = date('Y-m-d',$val_datefrom);

$val_dateto = strtotime("2015-09-30");
$val_dateto = date('Y-m-d',$val_dateto);

$dsdate = strtotime("2015-01-07");
$dsdate = date('Y-m-d',$dsdate);

echo $val_datefrom .'>='. $dsdate .'&&'. $val_dateto .'<='. $dsdate.'<br>';
var_dump($val_datefrom >= $dsdate && $val_dateto <= $dsdate);
var_dump($val_datefrom >= $dsdate);
var_dump($val_dateto <= $dsdate);

if($val_datefrom >= $dsdate && $val_dateto <= $dsdate){
  // some codes if true
}

I am sure my code is correct giving the exact value but still it gives me a null value.. I tried to debug my code and this is the result for var_dump()

2015-01-01>=2015-01-07&&2015-09-30<=2015-01-07
bool(false) bool(false) bool(false) 
2015-01-01>=2015-01-08&&2015-09-30<=2015-01-08
bool(false) bool(false) bool(false) 

any idea about this?

Upvotes: 2

Views: 54

Answers (1)

Toza
Toza

Reputation: 1358

While this is a different approach, did you consider using DateTime::diff()? It's a simple way to compare dates in PHP.

OOP:

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

Procedural:

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>

Output:

+2 days

You can make an if statement with this without the extra steps:

if(($val_datefrom->diff($dsdate)->format('%R%a') >= 0) 
&& ($val_dateto->diff($dsdate)->format('%R%a') <= 0)){ ... }

Read more about it here

Upvotes: 4

Related Questions