I don’t know any way to create timezones
customized, but I can suggest an alternative using timestamps.
Convert your date to a timestamp (int
), via strtotime
(if your date is in format string
) or DateTime::getTimestamp
(if it is in that format):
$timestamp1 = strtotime($hora1);
$timestamp2 = $hora2->getTimestamp();
Adjust difference in seconds of one of them (or both):
function ajustar($timestamp, $horas = 0, $minutos = 0, $segundos = 0)
{
return $timestamp + ($segundos + 60 * ($minutos + 60 * $horas);
}
$timestamp1_ajustado = ajustar($timestamp1);
$timestamp2_ajustado = ajustar($timestamp1, 0, 4);
Convert them back to one DateTime
, using DateTime::setTimestamp
:
$hora1_ajustada = new DateTime();
$hora1_ajustada->setTimestamp($timestamp1_ajustado);
$hora2_ajustada = new DateTime();
$hora2_ajustada->setTimestamp($timestamp2_ajustado);
Now you can calculate the difference between them normally. Full code:
function diferenca_ajustada($hora1, $hora2, $horas = 0, $minutos = 0, $segundos = 0)
{
$timestamp1 = $hora1->getTimestamp();
$timestamp2 = $hora2->getTimestamp() + $segundos + 60*($minutos + 60*$horas);
$ajustada1 = new DateTime();
$ajustada1->setTimestamp($timestamp1);
$ajustada2 = new DateTime();
$ajustada2->setTimestamp($timestamp2);
return $ajustada1->diff($ajustada2);
}
Example in Phpfiddle. Note: if dates are in different timezones, you may first need to convert them to UTC before comparing them:
function para_utc($timestamp)
{
return $timestamp - date("Z", $timestamp);
}
I didn’t know that
modify
, in fact it is much simpler than my solution. + 1– mgibsonbr