ใช้ new Date().getHours() ดึงชั่วโมงปัจจุบัน แล้ว Ternary Operator ตัดสินใจ
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p class="closeOrOpened"></p>
<script>
const gettingHours = new Date().getHours();
const actualHours = (gettingHours >= 10 && gettingHours < 18) ? 'Open' : 'Closed';
document.querySelector('.closeOrOpened').innerHTML = actualHours;
</script>
</body>
</html>
วิธีรันโปรแกรม
- บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
- คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor
ผลลัพธ์
เวลา 10:00-17:59 แสดง "Open" เวลาอื่นแสดง "Closed"