Oltre alla risposta molto utile di @ fyrye, questa è una soluzione alternativa per il bug menzionato ( questo ), che DatePeriod sottrae un'ora quando entra in estate, ma non aggiunge un'ora quando lascia l'estate (e quindi Europa / Berlino ha il suo 743 ore corrette ma ottobre ne ha 744 invece di 745):
Contando le ore di un mese (o qualsiasi periodo di tempo), considerando le transizioni dell'ora legale in entrambe le direzioni
function getMonthHours(string $year, string $month, \DateTimeZone $timezone): int
{
// or whatever start and end \DateTimeInterface objects you like
$start = new \DateTimeImmutable($year . '-' . $month . '-01 00:00:00', $timezone);
$end = new \DateTimeImmutable((new \DateTimeImmutable($year . '-' . $month . '-01 23:59:59', $timezone))->format('Y-m-t H:i:s'), $timezone);
// count the hours just utilizing \DatePeriod, \DateInterval and iterator_count, hell yeah!
$hours = iterator_count(new \DatePeriod($start, new \DateInterval('PT1H'), $end));
// find transitions and check, if there is one that leads to a positive offset
// that isn't added by \DatePeriod
// this is the workaround for https://bugs.php.net/bug.php?id=75685
$transitions = $timezone->getTransitions((int)$start->format('U'), (int)$end->format('U'));
if (2 === count($transitions) && $transitions[0]['offset'] - $transitions[1]['offset'] > 0) {
$hours += (round(($transitions[0]['offset'] - $transitions[1]['offset'])/3600));
}
return $hours;
}
$myTimezoneWithDST = new \DateTimeZone('Europe/Berlin');
var_dump(getMonthHours('2020', '01', $myTimezoneWithDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithDST)); // 743
var_dump(getMonthHours('2020', '10', $myTimezoneWithDST)); // 745, finally!
$myTimezoneWithoutDST = new \DateTimeZone('UTC');
var_dump(getMonthHours('2020', '01', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '10', $myTimezoneWithoutDST)); // 744
PS Se controlli un periodo di tempo (più lungo), che porta a più di quelle due transizioni, la mia soluzione alternativa non toccherà le ore contate per ridurre il potenziale di effetti collaterali divertenti. In questi casi, è necessario implementare una soluzione più complicata. Si potrebbe iterare su tutte le transizioni trovate e confrontare la corrente con l'ultima e controllare se è una con DST true-> false.
strftime()e dividere la differenza per 3600, ma funzionerà sempre? Accidenti a te, ora legale!