尝试使用HTML / JS显示如下内容:星期一11:03-我们当前处于开放状态
我尝试了一些不同的方法,但是只能使其部分工作。我想显示工作日/一天中的时间/以及商店是否开张。
这些是小时数:
Monday 10 a.m. - 5 p.m.
Tuesday 12 - 7 p.m.
Wednesday 10 a.m. - 5 p.m.
Thursday 10 a.m. - 5 p.m.
Friday 10 a.m. - 5 p.m.
Saturday 10 a.m. - 2 p.m.
Sunday Closed
function getDayOfWeek(date) {
const dayOfWeek = new Date(date).getDay();
var dateWithouthSecond = new Date();
dateWithouthSecond.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
return isNaN(dayOfWeek) ? null :
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dayOfWeek];
}
document.getElementById("demo").innerHTML = ( "It's " + getDayOfWeek(Date.now()) );
答案 0 :(得分:2)
正如其他人所建议的那样,您可以使用Date.prototype.toLocaleString()
并传递weekday
参数来检索星期几。
const OperatingHours = {
'Monday' : { 'open': 10, 'close': 17 },
'Tuesday' : { 'open': 12, 'close': 19 },
'Wednesday' : { 'open': 10, 'close': 17 },
'Thursday' : { 'open': 10, 'close': 17 },
'Friday' : { 'open': 10, 'close': 17 },
'Saturday' : { 'open': 10, 'close': 14 },
'Sunday' : { 'open': 1, 'close': -1 }
};
const greeting = (date) => {
const now = new Date(),
weekday = now.toLocaleString('en-us', { weekday: 'long' }),
formattedTime = now.toLocaleTimeString('en-US',
{ hour: '2-digit', minute: '2-digit' }),
currHour = now.getHours(),
{ open, close } = OperatingHours[weekday],
isOpen = currHour >= open && currHour <= close;
return isOpen
? `It's ${weekday} ${formattedTime} — we are currently open.`
: `Sorry, it's ${weekday} ${formattedTime} — we are currently closed.`;
};
console.log(greeting(new Date()));
答案 1 :(得分:1)
使用打开的小时数设置对象,然后进行如下比较。请注意,星期日已设置,因此介于两者之间没有任何值。
const HOURS_OPEN = {
"Monday": {"open": 10,"close": 16},
"Tuesday": {"open": 12,"close": 18},
"Wednesday": {"open": 10,"close": 16},
"Thursday": {"open": 10,"close": 16},
"Friday": {"open": 10,"close": 16},
"Saturday": {"open": 10,"close": 13},
"Sunday": {"open": 1,"close": -1}
}
let today = new Date();
let weekday = today.toLocaleString('en-us', {
weekday: 'long'
});
let currentHour = today.getHours();
let open = HOURS_OPEN[weekday].open;
let close = HOURS_OPEN[weekday].close;
let statusString = "";
if (currentHour >= open && currentHour <= close) {
statusString = `It's ${formatNow()}. We're open!`;
console.log(statusString);
} else {
statusString = `It's ${formatNow()}. Sorry, we're closed :(`;
console.log(statusString);
}
document.getElementById("demo").innerText = statusString;
function formatNow() {
let d = new Date();
let min = d.getMinutes();
let hr = d.getHours();
let ampm = "AM"
if (min < 10) {
min = "0" + min;
}
if (hr > 12) {
hr -= 12;
ampm = "PM";
}
return (`${hr}:${min} ${ampm}`);
}
<div id="demo"></div>