Comparison of PHP schedules

Asked

Viewed 223 times

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 some script I found on the internet... basically the variable $por_do_sol is a string with the time of sunset in my city, what I want to know how I do to compare with the current time and know if the sunset has passed the sunset.

1 answer

6


You can make the comparison by creating a new object of type DateTime Let him receive the time of the setting of the sun in his city, according to his example. After that, it is possible to create comparisons the way you want, because the class DateTime uses the timestamp encapsulated as value.

For your case, the code may 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 defining the timezone it will not be necessary to create an object DateTimeZone for the construction of objects DateTime, if the Directive gives the same value as the object, as in the example. To obtain the time zone index it is possible to use the function getOffset of your object DateTime, because it implements the DateTimeInterface.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.