Swap div visibility based on time / schedule

Issue

On my page I have two divs… one div I’d like to be visible from 10am to 6pm ( server time )…. and the other div for the remaining hours.

I tried a bunch of searches to find some sort of a javascript or jquery content swapper without any luck.. thanks for any suggestions?

<div id="day">content</div>

<div id="night">content</div>

I was able to get this working using only the following php:

<?php
$hour = strftime("%H");
if ($hour >= 02 && $hour < 05)
{
echo '<div id="div1">content block one </div>';
}
else
{
    echo '<div id="div2">content block two</div>';
}?>

However this solution doesn’t seem to work if I want to show the div from 8pm until 4am… is this because it is spanning more than one day? Thanks for any suggestions.

Solution

EDIT

The case you mentioned in your comment is a thorny one. So here is my revised-revised answer:

<?php
    $t0 = 20;        // from hour (inclusive) -- int, 0-23
    $t1 = 4;         // till hour (excluding) -- int, 0-23
    $t  = date('G'); // current hour (derived from current time) -- int, 0-23
    if ($t0 == $t1) {
        $in_range = NULL;
    } elseif ($t0 < $t1) {
        $in_range = ($t0 <= $t && $t < $t1);
    } else {
        $in_range = ($t1 <= $t && $t < $t0) == false;
    }
    /*
    echo $in_range === NULL
        ? 'from and till dates must be different'
        : ($in_range ? 'just in time' : 'wait till the time is right');
    */
    if ($in_range === false) {
        $s0 = mktime($t0, 0, 0); // lunch time
        $s  = time();            // current time
        if ($s0 < $s) {
            $s0 += 60 * 60 * 24; // late for lunch! now wait till tomorrow
        }
        $d0 = $s0 - $s;
        $dh = floor($d0 / 60 / 60);
        $dm = $d0 - $dh * 60 * 60; $dm = floor($dm / 60);
        $ds = $d0 - $dh * 60 * 60 - $dm * 60;
        echo sprintf("
            Current date...: %s<br />
            Target date....: %s<br />
            Time to go.....: %d hours, %d minutes, %d seconds
            ",
            date("Y-m-d h:i:s A", $s),
            date("Y-m-d h:i:s A", $s0),
            $dh,
            $dm,
            $ds
        );
    }
?>

Answered By – Salman A

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published