สร้าง Date Object ได้หลายวิธี โดยใช้ Constructor new Date()
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Date Object</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Date object in JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3> Click to create a date object and display it </h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
resEle.innerHTML = new Date();
});
</script>
</body>
</html>
วิธีสร้าง Date Object ทั้ง 4 แบบ
new Date()- วันที่/เวลาปัจจุบันnew Date(milliseconds)- มิลลิวินาทีนับจาก Jan 1, 1970new Date(dateString)- จาก String เช่น "2024-12-25"new Date(year, month, day, hours, minutes, seconds, ms)- ระบุค่าแต่ละส่วน (month เริ่มที่ 0)
ผลลัพธ์
กดปุ่มแล้วแสดงวันที่/เวลาปัจจุบันในรูปแบบ String มาตรฐาน เช่น "Wed Dec 25 2024 10:30:45 GMT+0700 (Indochina Time)"