Skip to content Skip to sidebar Skip to footer

Php Compare Two Dates

I have two dates in the format YYYY-MM-DD and I want to compare them do do some task. I tried this piece of code: $temp_date = strtotime($cu['date']); $temp_upto

Solution 1:

Nope, this isn't right. You're comparing two date strings. You want to compare the timestamps instead:

$temp_dateTS = strtotime($cu['date']);
$temp_uptoTS = strtotime($upto_date);

if ($temp_dateTS <= $temp_uptoTS) {
    # code...
}

This is also possible (and better) if you use DateTime class:

$temp_date = new DateTime($cu['date']);
$temp_upto = new DateTime($upto_date);

if ($temp_date <= $temp_upto) {
    # code...
}

Solution 2:

I'm not directly answering your question but I thinks it's better to user php DateTime object.

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);

Post a Comment for "Php Compare Two Dates"