jQuery-根据日期和时间显示/隐藏div [英] jquery - show / hide div depending on day and time

查看:93
本文介绍了jQuery-根据日期和时间显示/隐藏div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据日期和时间显示特定的div.

I am trying to show a specific div depending on the day and time.

因此,如果一天在星期一-星期五之间,并且时间在9am-5:30 pm之间,

So if the Day is between Monday - Friday and the Time is between 9am - 5:30pm,

然后它将显示div = class.open

then it will show div = class.open

如果在该时间之前或之后,它将显示div = class.closed

if before or after that time, it will show div = class.closed

我有以下代码可以正常显示.open div,即星期一至星期五上午9点至下午5点.它将显示从0am到9am的.closed div.但是我需要它在周一至周五上午9点至下午5点以外的任何时间显示关闭的div.

I have the following code that works to show the .open div when open, Monday-Friday 9am to 5pm. And it will show the .closed div from 0am to 9am. But I need it to show the closed div anytime it is outside of Monday-Friday 9am-5pm.

所以我有2个问题:

  1. 如果不在周一至周五的上午9点至下午5点,如何显示.closed div节目?

  1. How do I have the .closed div show whenever it is not Monday-Friday 9am to 5pm?

如何添加分钟,例如从上午8:30开放到下午5:30?

How can I add minutes in, like open 8:30am to 5:30pm?

代码

<div class="hours">We are OPEN</div>
<div class="closed">We are CLOSED</div>
$(document).ready(function () {

    var d = new Date();
    var dayOfWeek = d.getDay();
    var hour = d.getHours();

    // open hours Monday - Friday 9am - 5:pm = open
    if (dayOfWeek === 6 || dayOfWeek === 0 || hour <= 9 || hour >= 17) {
        $('.hours').hide();
    }
    // closed any other time than above * working from 0am -9am but none other
    if (dayOfWeek === 6 || dayOfWeek === 0 || hour <= 0 || hour >= 9) {
        $('.closed').hide();
    }


});

这里是示例: JSFiddle

推荐答案

比较 getTime() 的指定日期.

Compare the getTime()'s of the dates specified.

下面的代码设置当天的开放时间和关闭时间,并检查当前时间是否在这两个时间戳之间.

The below code sets Opening Time and Closing Time of the current day and checks whether the current time is between those two time stamps.

var Now = new Date(),
  CurrentDay = Now.getDay(),
  OpeningTime = new Date(Now.getFullYear(), Now.getMonth(), Now.getDate(), 8, 30),
  ClosingTime = new Date(Now.getFullYear(), Now.getMonth(), Now.getDate(), 17, 30),
  Open = (Now.getTime() > OpeningTime.getTime() && Now.getTime() < ClosingTime.getTime());

if (CurrentDay !== 6 && CurrentDay !== 0 && Open) {
    $('.openstatus').toggle();
}

.hours {
  display:none;  
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hours openstatus">We are OPEN</div>
<div class="closed openstatus">We are CLOSED</div>

这篇关于jQuery-根据日期和时间显示/隐藏div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆