Search code examples
phpcountdownhour

How do you Calculate Hours from the Beginning of the Year in PHP


I Was Just Wondering How do you Calculate Hours from the Beginning of the Year in PHP 7.1

It's for a countdown clock that is precise


Solution

  • You can just do:

    $diff = date_create()->diff(new DateTime("first day of January ".date("Y")));
    $hours = $diff->format("%a")*24 + $diff->h; 
    

    As requested here's a way to handle daylight savings:

    $transitions = (new DateTimeZone(date_default_timezone_get()))->getTransitions();
    
    $thisYearsTransitions = array_values(array_filter($transitions, function ($v) {
         return substr($v["time"],0,strlen(date("Y"))) == date("Y");
    }));
    if (count($thisYearsTransitions) == 2 && date_create($thisYearsTransitions[0]) < date_create() && count($thisYearsTransitions)>0 && date_create($thisYearsTransitions[1]) > date_create()) {
        $hours = $hours + ($thisYearsTransitions[0]["offset"]-$thisYearsTransitions[1]["offset"] > 0?1:-1);
    }
    

    What this would do is get the DST transitions for this year and if the current date falls after the first and before the second transition it will add/subtract an hour (depending on timezone). Not sure if this would work, have not tested it, but it should.