toLocaleString() แสดงวันในสัปดาห์เป็นภาษาไทย เดือนแบบเต็ม วันที่ และปีในรูปแบบ พ.ศ. (Buddhist Era) ในเบราว์เซอร์ที่รองรับ Thai locale
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8">
<title>Page Title</title>
<style>
.text-right { text-align: right; }
.text-sm { font-size: 0.875rem; }
.md\:text-base { font-size: 1rem; }
.font-medium { font-weight: 500; }
.font-light { font-weight: 300; }
</style>
</head>
<body>
<div id="datetime" class="text-right text-sm md:text-base">
<div id="current-date" class="font-medium">กำลังโหลดวันที่...</div>
<div id="current-time" class="font-light">กำลังโหลดเวลา...</div>
</div>
<script>
function updateDateTime() {
const now = new Date();
const options = {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long'
};
const timeOptions = {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
};
document.getElementById('current-date').textContent = now.toLocaleString('th-TH', options) ;
document.getElementById('current-time').textContent = now.toLocaleTimeString('th-TH', timeOptions) + ' น.';
}
// Call once immediately
updateDateTime();
// Update every second
setInterval(updateDateTime, 1000);
</script>
</body>
</html>
📌 คำอธิบาย options ที่คุณสามารถใช้กับ toLocaleString() หรือ toLocaleDateString() / toLocaleTimeString():
| ตัวเลือก (option) | ความหมาย | ตัวอย่างผลลัพธ์ |
|---|
weekday | 'long' หรือ 'short' | วันพุธ / พ. |
year | 'numeric' หรือ '2-digit' | 2568 / 68 |
month | 'long', 'short', 'numeric' | พฤษภาคม / พ.ค. / 5 |
day | 'numeric' หรือ '2-digit' | 29 / 29 |
hour, minute, second | 'numeric' หรือ '2-digit' | 9 / 09 |
hour12 | true (AM/PM), false (24ชม.) |
สมชาย เข้าใจเลยครับ
ตอบลบ