-5

So here's what I'm trying to do - I have the following code:

<div id="on">
<p>We are: <span class="onair"><a href="#">ON AIR</a></span></p>
</div> 
<div id="off">
<p>We are: <span class="offair"><a href="#">OFF AIR</a></span></p> 
</div>

And what I'd like to do is "show" the "on" div on Tuesday's from 3pm to 4pm (server time), while simultaneously hiding the "off" div - and then switch that around for every other date/time.

?

qodeninja
  • 10,946
  • 30
  • 98
  • 152
pearible
  • 1
  • 1
  • 2
  • 2
    What all have you tried? I'm a little skeptical of this question because it's not tagged with a server side language `i.e. ASP.NET, PHP, etc.` As far as I know you cannot get the server time using JavaScript alone. It would take an `AJAX` call to the server to get that information. JavaScript is client side not server side. – War10ck Feb 12 '13 at 17:56
  • 1
    If you could use something with PHP, then we could probably help you. In PHP, you could use the time() function to get the current time and use that with Javascript to show/hide the class onair/offair. – Nina Feb 12 '13 at 18:00
  • You can do this with javascript, but the problem is how will you know what the server time is? You need a server-side technology (PHP, Ruby, etc) to render the server's timestamp. If you use only javascript you're only going to get the client-side (browser) timestamp. You need to provide as much info to the community as possible so we can help you. – qodeninja Feb 12 '13 at 18:03

3 Answers3

1

If you use PHP you can do logic statements on the server-side to render the exact information you need instead of calculating it later on the client side.

(Client side solutions work too if you dont care about where the time is coming from)

(1) You can have the server render javascript for you that you can use in a script

//if you want the server's time you can do this:
<?php $timestamp = time(); ?>

//render variables in javascript instead of html
<?php 
  echo <<<EOD
    <script>
     var timestamp = ${timestamp}
     //then later in your javascript process the timestamp logic to update the dom
    </script>
  EOD;
?>

(2) You can also have the server render a className in the body tag based on whether or not a condition is true or false. (This is my preferred method usually)

//onAirClass( min, max, timestamp ) returns className 
//this function returns onair or offair class if the timestamp is in range
function onAirClass( timeMin, timeMax, timestamp ){
  if( timestamp >= timeMin && timestamp <= timeMax ){
    return 'onair';
  }
  return 'offair'
}

//using onAirClass( min, max, timestamp ) 
<?php $bodyClass = $bodyClass . ' ' . onAirClass( $timestamp ); ?>
<?php echo "<body class='${bodyClass}'>"; ?>

then in your styles you can have the elements you want to hide or show based on class inheritance from the body tag.

Check out the PHP time function to create new time strings, and do time calculations for your onAirClass() function

How to check the time between a given time range


UPDATED

Corrected PHP syntax errors

@maerics solution is OK, depending on what you want to do, just don't EVER do anything like this:

var timestamp = $('#server-timestamp').text();

Ultimately, there are many ways to do the same thing, but some things are more 'right' than others.

There are reasons to do some calculations on the client side vs the server side, and vice versa. As a newbie developer, just make sure that whatever method you use:

  • is simple
  • is efficient (doesnt do anything unnecessary or redundant)
  • falls in line with best practices
Community
  • 1
  • 1
qodeninja
  • 10,946
  • 30
  • 98
  • 152
  • I'm using PHP - though I'm not sure I understand enough of it to implement your answer. – pearible Feb 12 '13 at 18:15
  • What if the user loads the page at 2:55pm (server time) and does not reload it? At 3pm server time the page will display the wrong information to the end-user! The tiny overhead of client-side scripting is easily worth avoiding this problem. – maerics Feb 12 '13 at 18:16
  • @maerics, he/she is not using an AJAXY-solution to keep a constant time out of the on-air status. Based on what this person is trying to accomplish (render the UI based on the server time), they shouldn't be using jQuery for this when the server can easily render it. I think you may have over-engineered the solution adding a bunch of client-side timeout stuff, the user did not ask for this. – qodeninja Feb 12 '13 at 18:21
  • my JavaScript skills are almost up to the quality of "poor" - so I'm with you on everything except the isOnAir function – pearible Feb 12 '13 at 18:30
0

Have the server provide a timestamp when it generates the page and have the client also generate a timestamp when it loads the page so that you can calculate the time offset between the two systems.

Then you can call a function on some interval that checks the current server time to see if it is within the 3pm-4pm period and show/hide the target elements as needed.

From the server:

<div id="server-timestamp" style="display:none">2013-02-12T18:01:19Z</div>

On the client:

$(document).on('load', function() {
  var serverTime = new Date($('#server-timestamp').text())
    , clientTime = new Date()
    , offsetMilliseconds = (clientTime - serverTime);
  setInterval(function() {
    // If server time is 3pm-4pm then hide/show divs...
  }, 1000 /* every second */);
});
maerics
  • 151,642
  • 46
  • 269
  • 291
  • Sorry - should have specified PHP – pearible Feb 12 '13 at 18:10
  • @maerics, I still disagree with you (Your code is not efficient use of server-side technology) because you should not be doing stuff like $('#server-timestamp') .. really? Load and iterate over the DOM just to figure out what string the server returned? No. You can use just output the value in a javascript var. – qodeninja Feb 12 '13 at 18:29
0

Actually this can be accomplished using just JavaScript without any server-side code, by using your timezone offset.

Here's a function you can use:

var onAir = function (day, start, end, timezone) {
    var local, utc, show, days, onAir, startValues, endValues, startTime, endTime, startMinutes, endMinutes, showMinutes;

    // by default, we are not on air    
    onAir = false;

    // map day numbers to indexes
    days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Firday', 'Saturday'];

    // convert start/end times to date objects
    startValues = start.split(':');
    endValues = end.split(':');
    startTime = new Date();
    endTime = new Date();
    startTime.setHours(startValues[0], startValues[1]);
    endTime.setHours(endValues[0], endValues[1]);

    // add the hours minutes together to get total minutes
    startMinutes = (startTime.getHours() * 60) + startTime.getMinutes();
    endMinutes = (endTime.getHours() * 60) + endTime.getMinutes();

    // get the current local time
    local = new Date();

    // get the current time in the show's timezone
    utc = local.getTime() + (local.getTimezoneOffset() * 60000);
    show = new Date(utc + (3600000*timezone));

    // convert the show hours + minutes to just minutes
    showMinutes = (show.getHours() * 60) + show.getMinutes();

    // test to see if the show is going on right now
    if (days[show.getDay()] === day && (showMinutes >= startMinutes && showMinutes <= endMinutes)) {
        onAir = true;
    }

    return onAir;
}

// example: Air time is Tuesday between 1-2pm Central Time (-6)
var texasShowOnAir = onAir('Tuesday', '13:00', '14:00', '-6'));

// now check if we are on air
if (texasShowOnAir) {
    // do stuff here...
}

You can now use this function like this:

var check = onAir('DAY', 'STARTTIME', 'ENDTIME', 'YOURTIMEZONE');

This will return a true/false. Be sure and use 24 hour format.


I would even argue that this is better than using your server's timestamp, because often (especially if you have shared hosting), your server can be set in a different timezone than you.

Here's a demo fiddle: http://jsfiddle.net/stevenschobert/mv54B/

Steven Schobert
  • 4,201
  • 3
  • 25
  • 34
  • agree with 'you can do this on the client side' in that you dont have to use the server's time, and it saves you the trouble of having to do any PHP and less work is always nice. – qodeninja Feb 12 '13 at 19:22
  • I will say this is a solution but it is not based on the Server time like the OP asked. You're right in that it **can** be accomplished with just JavaScript but the time is the client time not the server time. The server time **cannot** be used on the client without some sort of server side scriptiong. – War10ck Feb 12 '13 at 21:47
  • @War10ck Yes, while the question writer did mention server time, I believe it was only because they assumed that was the only way to accurately obtain the time of their show (3-4pm). When in actuality, the server time is not guaranteed to be correct. The method I proposed doesn't care what the client time OR server time is. It simply calculates the Universal time using a timezone, which is more reliable. – Steven Schobert Feb 12 '13 at 22:48