这是我写的东西。相当粗糙,但考虑到关闭时间在午夜之后的情况。
也可在 Gist 获得:https ://gist.github.com/vtntimo/b5c724371bfb27bfb080
如果你创造了改进,请联系我:)
/*
Operating hours check
=====================================
- Checks if something is open right now
- Supports closing times going over midnight
- Feel free to use in whatever you need :)
- If you make improvements, please inform me!
Example:
// Setting operating hours
// Key 0 is sunday, 1 is monday and so on
var hours = [
// Sunday
{
open: '08:00',
close: '16:00'
},
// Monday
{
allday: true // Open all day
},
// Tuesday
false, // Closed all day
// Wednesday
{
open: '08:00',
close: '16:00'
},
// Thursday
{
open: '08:00',
close: '16:00'
},
// Friday
{
open: '08:00',
close: '16:00'
},
// Saturday
{
open: '08:00',
close: '16:00'
},
];
if(isOpen(hours)) {
alert("We're open!");
}
else {
alert("We're closed!");
}
*/
function isOpen(hours) {
var now = new Date();
var today = now.getDay();
var yesterday = today - 1;
if(yesterday < 0) yesterday = 6;
// Check today's opening hours
if(hours[today]) {
// It's open all day today
if(hours[today].allday) {
return true;
}
// Not open all day
else {
var open = hours[today].open;
var close = hours[today].close;
// Check if the location is open
if(checkOpenHours(now,now,open,close)) {
return true;
}
}
}
// Check yesterday's opening hours in case of closing after midnight
if(hours[yesterday]) {
// Not open all day (possibly closing after midnight)
if(!hours[yesterday].allday) {
var open = hours[today].open;
var close = hours[today].close;
var yesterday_date = new Date(now.getFullYear(), now.getMonth(), (now.getDate()-1), 0, 0, 0, 0);
if(checkOpenHours(now,yesterday_date,open,close)) {
return true;
}
}
}
// Not open
return false;
}
/*
Check if "now" is within operating hours
*/
function checkOpenHours(now, operatingDate, open, close) {
// Splitting times to array
var o = open.split(":");
var c = close.split(":");
// Hours not in proper format
if(o.length < 2 || c.length < 2) {
return false;
}
// Converting array values to int
for(var i = 0; i < o.length; i++) {
o[i] = parseInt(o[i]);
}
for(var i = 0; i < c.length; i++) {
c[i] = parseInt(c[i]);
}
// Set opening Date()
var od = new Date(operatingDate.getFullYear(), operatingDate.getMonth(), operatingDate.getDate(), o[0], o[1], 0, 0);
// Set closing Date()
var closingDay = operatingDate.getDate();
// Closing after midnight, shift day to tomorrow
if(o[0] > c[0]) {
closingDay++;
}
var cd = new Date(operatingDate.getFullYear(), operatingDate.getMonth(), closingDay, c[0], c[1], 0, 0);
// Is within operating hours?
if(now > od && now < cd) {
return true;
}
else return false;
}