Comparing dates

Dates can be compared only if they are stored in the same format. PHP does not have a variable of type „data”, it must be stored as a timestamp or text. In turn, the form text can be extremely varied, depending on national standards or fantasy programmer – here you can see the advantage timestamp format.mensclub24


If the date is already in the same form, they can be compared simply by the comparison operator. In addition, if the date is a timestamp format, you can use mathematical operators (<and>) to determine which date is „later”.
Example

<?php

$time1 = mktime (19, 30, 0);
$time2 = mktime (20, 0, 0);

if ($time1> $time2) {
echo „Time variable time1 is later”;
} else {
echo „Time variable time2 is later”;
}

?>

Comparing dates in timestamp format is easy, if you need to compare with precision „to the second.” The matter is complicated, if you need to say, for example, whether two dates are the same day. To confirm that you have to break down the date and comparable components. Such a code can be transferred to a separate function, to easily compare date.
Example

<?php

Sameday function ($ts1, $ts2)
{
if (date ( „Y” $ts1)! = date ( „Y” $ts2)) {
return False;
}
if (date ( „m”, $ts1)! = date ( „m”, $ts2)) {
return False;
}
if (date ( „d”, $ts1)! = date ( „d”, $ts2)) {
return False;
}
return true;
}

$date1 = mktime (19, 30, 0, 12, 10, 2001);
$date2 = mktime (10, 12, 0, 12, 10, 2001);
$date3 = mktime (19, 30, 0, 12, 11, 2001);

if (Sameday ($date1, $date2)) {
echo „Dates 1 and 2 are of the same day”;
}

if (Sameday ($date1, $date3)) {
echo „Dates 1 and 3 are of the same day”;
}

?>

Cookies help us deliver our services. By using our services, you agree to our use of cookies. More Info | Close