ใช้ new Date().getFullYear() ดึงปีปัจจุบันมาแสดง
ตัวอย่างโค้ด
<!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>
<h1> The Current Year=<span id="theCurrentYear"></span> </h1>
<script>
document.getElementById("theCurrentYear").innerHTML = new Date().getFullYear();
</script>
</body>
</html>
วิธีรันโปรแกรม
- บันทึกไฟล์ชื่อ "anyName.html" หรือ "index.html"
- คลิกขวาที่ไฟล์ เลือก "Open with Live Server" ใน VS Code Editor
ผลลัพธ์
แสดงปีปัจจุบัน (เช่น 2024) ในหน้าเว็บ