How to compare two dates in php if dates are in format \'03_01_12\'
and \'31_12_11\'
.
I am using this code:
$date1=date(\'
Guys Please don't make it so complex The simple answer bellow
$date1=date('d_m_y');
$date2='31_12_11';
$date1=str_replace('_', '-', $date1);
$date2=str_replace('_', '-', $date2)
if(strtotime($date1) < strtotime($date2))
echo '1 is small ='.strtotime($date1).','.$date1;
else
echo '2 is small ='.strtotime($date2).','.$date2;
I just have added two more lines with your code
You will have to make sure that your dates are valid date objects.
Try this:
$date1=date('d/m/y');
$tempArr=explode('_', '31_12_11');
$date2 = date("d/m/y", mktime(0, 0, 0, $tempArr[1], $tempArr[0], $tempArr[2]));
You can then perform the strtotime()
method to get the difference.
Using DateTime::createFromFormat:
$format = "d_m_y";
$date1 = \DateTime::createFromFormat($format, "03_01_12");
$date2 = \DateTime::createFromFormat($format, "31_12_11");
var_dump($date1 > $date2);
The date_diff() function returns the difference between two DateTime objects.
If the first date is before the second date a positive number of days will be returned; otherwise a negative number of days:
<?php
$date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
output will be "+272 days" ;
changing $date1 = "2014-03-15"
<?php
$date1=date_create("2014-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
?>
Output will be "-93 days"
I think this one is very simple function
function terminateOrNotStringtoDate($currentDate, $terminationdate)
{
$crtDate = new DateTime($currentDate);
$termDate = new DateTime($terminationdate);
if($crtDate >= $termDate)
{
return true;
} else {
return false;
}
}
Extending @nevermind's answer, one can use DateTime::createFromFormat: like,
// use - instead of _. replace _ by - if needed.
$format = "d-m-y";
$date1 = DateTime::createFromFormat($format, date('d-m-y'));
$date2 = DateTime::createFromFormat($format, str_replace("_", "-",$date2));
var_dump($date1 > $date2);