Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ekaitzastiz's avatar

year with 8759 hours , want 8760 hours

I am looping a year with carbon, incrementing on hour each loop. I think, because time or hour change I am getting 8759 hours. 2015-03-29 02:00 is missing (when time changes) I am trying with different time zones, but I don't see any change. Does anyone know how to get the loop for all the hours? What timezone should I use?

Or do I need to add out of the loop detecting the last sunday of march 02:00? I already have this done in other place, but I think that has to be a way to loop 8760 hours without adding one hour manually.

thank you

0 likes
6 replies
toniperic's avatar

How are you looping over a year with Carbon? What are elements in the array you're looping?

Show us some code.

ekaitzastiz's avatar
          $carbon = new Carbon();
           // ->setTimeZone()...
           $actualHour = $carbon->createFromFormat('Y-m-d H:i',$this->firstHour);
           $periodTable =  $this->periodFactory($periodTableType);


           while($actualHour->format('Y-m-d H:i') != $this->lastHour)
           {
               $p = $periodTable->getPeriodFromDateTime($actualHour->format('Y-m-d H:i'));
               $this->periods[] = [
                   'tabla_periodo' => $pTable,
                   'fecha_hora'    => $actualHour,
                   'aino'          => $actualHour->format('Y'),
                   'mes'           => $actualHour->format('m'),
                   'dia'           => $actualHour->dayOfWeek,
                   'fecha'         => $actualHour->format('Y-m-d'),
                   'hora'          => $actualHour->format('H'),
                   'periodo'       => $p,
                   'mes_periodo'   => $actualHour->format('m').$p,
               ];
               $actualHour->addHour();

           }


otepas's avatar
otepas
Best Answer
Level 13

@ekaitzastiz I think that behaviour is correct. There is no 2015-03-29 02:00, since that is the same as 2015-03-29 03:00.

The hour you are missing is in 2015-10-25 02:00. Since in October the clocks go back, 2015-10-25 02:00 is two hours long.

ekaitzastiz's avatar

I am storing each hour "period type" for energy consumption. I don't know how it is in other countries but in Spain each hour has a period. I need to take a quarter measure and see what period belongs to (P3 table, p1,p2,p3, or P6: p1,p2,p3p,p4,p5,p6). So i have to build the calendar with each hour to be able check all the measures or readings. For example, 2015-05-02 02:15 , 2015-05-03 02:30.... 02:00-03:00: each hour has a "period value".

Snapey's avatar

Create your entries in UTC. This is not subject to any daylight savings adjustments.

1 like

Please or to participate in this conversation.