Các phương thức lấy thành phần ngày/giờ từ đối tượng Date:
| Phương thức | Mô tả |
|---|---|
| getFullYear() | Năm 4 chữ số. |
| getMonth() | Tháng (0-11). |
| getDate() | Ngày trong tháng (1-31). |
| getHours() | Giờ (0-23). |
| getMinutes() | Phút (0-59). |
| getSeconds() | Giây (0-59). |
| getMilliseconds() | Mili giây (0-999). |
| getTime() | Mili giây từ 1/1/1970. |
| getDay() | Thứ trong tuần (0-6). |
| Date.now() | Mili giây từ 1/1/1970 UTC. |
Ví dụ
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { font-size: 18px; font-weight: 500; } </style> </head> <body> <h1>Các phương thức Date trong JavaScript</h1> <div class="sample"></div> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3> Nhấn nút để lấy một số phương thức Date </h3> <script> let sampleEle = document.querySelector(".sample"); let date = new Date(); document.querySelector(".Btn").addEventListener("click", () => { sampleEle.innerHTML += "getFullYear() = " + date.getFullYear() + "<br>"; sampleEle.innerHTML += "getMinutes() = " + date.getMinutes() + "<br>"; sampleEle.innerHTML += "Date.now() = " + Date.now() + "<br>"; sampleEle.innerHTML += "getMonth() = " + date.getMonth() + "<br>"; }); </script> </body> </html>
Kết quả
Hiển thị năm, phút, timestamp, tháng hiện tại.