How to show Open/Closed based on time records with

2020-04-06 16:09发布

I'm trying to display Open or Closed based on a company's time for that specific date using Javascript. I'm using a theme Listify on WordPress which customers can list their businesses. They have the option to put in their business hours for each day of the week. I want to be able to use that data which is stored within a span and then determine if the business is open or closed and display that.

Here is the code I have so far:

<p class="business-hour" itemprop="openingHours" content="Monday 8am-17pm">
    <span class="day">Monday</span>
    <span class="business-hour-time">
         <span class="start">8:30 am</span> – <span class="end">5:30 pm</span>
   </span>
</p>

This is just for one day, but you should get the idea. I've been looking all over for hours to find something like this. All I can find is coding with the specific hours already defined within Javascript. I want to be able to use the classes start and end to create a the open or closed. Is this possible? I would think it is. I just can't seem to do it correctly.

I've been practicing here but can't seem to figure anything out: http://codepen.io/tetonhiker/pen/KzxRzg

Thanks!

1条回答
男人必须洒脱
2楼-- · 2020-04-06 16:50

I've modified your code a little, making use of date.js:

http://codepen.io/anon/pen/VaGdBK

var da = new Date();
document.getElementById("display").innerHTML = da.toDateString();




//gets the current time. 
//var d = new Date();
var x = document.getElementsByClassName("start")[0].innerText;
var z = document.getElementsByClassName("end")[0].innerText;
//var o = parseInt(x,10);
//var c = parseInt(z,10);

var startTime = Date.parseExact(x, "h:mm tt");
var endTime = Date.parseExact(z, "h:mm tt");

if (da.between(startTime, endTime)){
    $(".open").show();
    $(".closed").hide();
}
else {  
    $(".closed").show();
    $(".open").hide();
}
.open, .closed {
  display: none;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
<span class="day">Monday </span>
<span class="start">8:30 am</span> - 
<span class="end">5:30 pm</span>
<br>
<span id="display"></span>
<div class="open">Shop is open</div>
<div class="closed">Shop is closed</div>

I haven't looked into it sufficiently so I don't know how it works regarding the timezone. You might have to adjust what I've posted to account for that.

Also: added a CSS rule to avoid the brief flash of both open and closed being displayed before one of them is hidden by jQuery.

查看更多
登录 后发表回答