根据服务器日期和时间显示和隐藏


show and hide based on server date and time

下面是我要做的事情-我有以下代码:

<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>

我想做的是在周二下午3点到4点(服务器时间)"显示"开启"div,同时隐藏"关闭"div,然后每隔一个日期/时间切换一次。

如果您使用PHP,您可以在服务器端执行逻辑语句来呈现所需的确切信息,而不是稍后在客户端进行计算。

(如果你不在乎时间从哪里来,客户端解决方案也可以工作)

(1) 您可以让服务器为您呈现可以在脚本中使用的javascript

//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) 您还可以让服务器根据条件是否为true或false在body标记中呈现className。(这通常是我喜欢的方法)

//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}'>"; ?>

然后,在样式中,可以根据body标记的类继承来隐藏或显示要隐藏或显示的元素。

查看PHP时间函数以创建新的时间字符串,并为onAirClass()函数进行时间计算

如何检查给定时间范围之间的时间


更新

更正了PHP语法错误

@maerics的解决方案是可以的,这取决于你想做什么,只是永远不要做这样的事情:

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

归根结底,有很多方法可以做同样的事情,但有些事情比其他事情更"正确"。

有理由在客户端与服务器端进行一些计算,反之亦然。作为一个新手开发人员,只要确保无论你使用什么方法:

  • 很简单
  • 高效(不做任何不必要或多余的事情)
  • 符合最佳实践

实际上,这可以通过使用时区偏移量,只使用JavaScript而无需任何服务器端代码来完成。

这里有一个你可以使用的功能:

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...
}

你现在可以这样使用这个功能:

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

这将返回一个true/false。请务必使用24小时制。


我甚至认为这比使用服务器的时间戳更好,因为通常(尤其是如果您有共享主机),您的服务器可以设置在与您不同的时区。

这是一个演示小提琴:http://jsfiddle.net/stevenschobert/mv54B/

让服务器在生成页面时提供时间戳,让客户端在加载页面时也生成时间戳,以便计算两个系统之间的时间偏移。

然后,您可以每隔一段时间调用一个函数,检查当前服务器时间是否在下午3点到4点之间,并根据需要显示/隐藏目标元素。

来自服务器:

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

在客户端:

$(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 */);
});