Comparison of PHP schedules

6
date_default_timezone_set ( "America/Sao_Paulo" );
$dtz = new DateTimeZone('America/Sao_Paulo');
$dt = new DateTime('now', $dtz);
$offset = $dtz->getOffset( $dt ) / 3600;
$por_do_sol = date_sunset(time(), SUNFUNCS_RET_STRING, -20.7965404, -49.3826269, $zenith = ini_get("date.sunset_zenith"), $offset);

I adapted a script I found on the internet ... basically the variable $ por_do_sol is a string with the sunset time in my city, which I want to know how do I compare with the current time and know if already passed the sunset.

    
asked by anonymous 23.02.2015 / 21:37

1 answer

6

You can make the comparison by creating a new object of type DateTime that receives the sunset time in your city, as shown by your example. After that, you can create comparisons the way you want, because the DateTime class uses the timestamp encapsulated as value.

For your case, the code could be as follows:

<?php
date_default_timezone_set("America/Sao_Paulo");

$dt = new DateTime('now');
$offset = $dt->getOffset() / 3600;
$por_do_sol = date_sunset(time(), SUNFUNCS_RET_STRING, -20.7965404, -49.3826269, $zenith = ini_get("date.sunset_zenith"), $offset);
$dtp = new DateTime($por_do_sol);

if ($dtp < $dt) {
    echo 'Já passou o pôr do sol.';
} else {
    echo 'Não passou o pôr do sol.';
}

Note: I suggest some simplifications, as when setting the timezone directive, it is not necessary to create a DateTimeZone object for the construction of DateTime objects, if the directive informs the same value as the object, as in example. To obtain the time zone index, you can use the getOffset function of your DateTime object, as it implements DateTimeInterface .

    
24.02.2015 / 03:39