Search code examples
phptimercountdowncountdowntimer

[PHP]Count down to specific times on a specific day


I'm making an automatic countdown to an event that starts 2-3 times a day at different times.

The event starts every 7 hours, so one day there are 4 events and the other 3.

Example: https://i.sstatic.net/IvYbh.png

$monday    = array( '02:00', '09:00', '16:00', '23:00' );
$tuesday   = array( '06:00', '13:00', '20:00'          );
$wednesday = array( '03:00', '10:00', '17:00'          );
$thursday  = array( '00:00', '07:00', '14:00', '21:00' );
$friday    = array( '04:00', '11:00', '18:00'          );
$saturday  = array( '01:00', '08:00', '15:00', '22:00' );
$sunday    = array( '05:00', '12:00', '19:00'          );

How to make the countdown run to the next event?

Example: if it is Monday, 01:30, it should say 30min left

I already made the countdown part:

 $hours = floor($this->sec / 3600);
 $minutes = floor(($this->sec / 60) % 60);
 $seconds = $this->sec % 60;
 return "$hours" . ' hours ' . "$minutes" .  ' minutes ' . "$seconds" . ' seconds';

Update: I know that the PHP won´t update just on itself. I will refresh the page manually.


Solution

  • function days_hours_minutes_from_now($date)
    {
      $now = time();
      $your_date = strtotime($date);
      $datediff = $your_date - $now;
      echo "days: " .floor($datediff/(60*60*24));
      echo " hours: " .floor($datediff/(60*60)) % 24; //hours
      echo " minutes: " .floor($datediff/(60)) % 60; //minutes
      echo " seconds: " .$datediff % 60; //seconds
    }
    
    days_hours_minutes_from_now("2015-08-19 13:52:28");
    

    days: 1 hours: 0 minutes: 14 seconds: 56

    Hasn't been tested thoroughly, but should be close to what you're looking for.

    You need to compare the time against when the event starts to get a countdown.

    However, as RiggsFolly rightly pointed out, unless you do this in javascript, your countdown isn't going to update in the user's browser unless they refresh the page.

    Edit:

    Now, if you wanted to ensure you always returned the time remaining until the next event, then you can loop through a series of dates, sorted in ascending order, and return the first result where the day is a non-negative value. If any date exceeds the current date/time, day will equal -1