วิธีการจัดรูปแบบวันเวลาใน JavaScript

JavaScript DateTime Format

ISO Format (มาตรฐานสากล)
  • ใช้ toISOString()
  • ผลลัพธ์เป็นรูปแบบ YYYY-MM-DDTHH:mm:ss.sssZ
const d = new Date();
console.log(d.toISOString()); 
// "2025-12-08T09:26:00.000Z"

เหมาะกับการเก็บข้อมูลในฐานข้อมูลหรือส่งต่อ API เพราะเป็นมาตรฐานเดียวกันทุกที่

การแสดงผลตาม Locale (ภาษาหรือประเทศ)
ใช้ toLocaleDateString() และ toLocaleTimeString()
const date = new Date();
console.log(date.toLocaleDateString("en-US")); // "12/8/2025"
console.log(date.toLocaleDateString("th-TH")); // "8/12/2568" (พุทธศักราช)
console.log(date.toLocaleTimeString("en-GB")); // "17:26:00"

ข้อดีคือจะแสดงผลตามรูปแบบของประเทศ/ภาษา เช่น ไทยจะเป็น พ.ศ. โดยอัตโนมัติ

Intl.DateTimeFormat (ยืดหยุ่นที่สุด)
const date = new Date();
const formatter = new Intl.DateTimeFormat("th-TH", {
  year: "numeric",
  month: "long",
  day: "numeric",
  hour: "2-digit",
  minute: "2-digit",
});
console.log(formatter.format(date));
// "8 ธันวาคม 2568 17:26"

สามารถกำหนดได้ว่าจะให้แสดงปี เดือน วัน ชั่วโมง นาที แบบสั้น/ยาว/ตัวเลข

การสร้างรูปแบบเอง (Custom Format)
const date = new Date();
const formatted = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} 
${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
console.log(formatted);
// "2025-12-8 17:26:30"

วิธีนี้เหมาะเมื่อคุณต้องการรูปแบบเฉพาะที่ไม่มีในฟังก์ชันมาตรฐาน

ตารางเปรียบเทียบ
วิธีใช้ ข้อดี ข้อเสีย ตัวอย่างผลลัพธ์
toISOString() มาตรฐาน, ใช้กับ API ได้ดี เป็น UTC เสมอ 2025-12-08T09:26:00.000Z
toLocaleDateString() แสดงตามภาษา/ประเทศ ปรับแต่งได้น้อย 8/12/2568
Intl.DateTimeFormat ปรับแต่งได้ละเอียด, รองรับหลายภาษา เขียนโค้ดยาวขึ้นเล็กน้อย 8 ธันวาคม 2568 17:26
Manual (สร้างเอง) ควบคุมได้เต็มที่ โค้ดยาว, ต้องจัดการเองทั้งหมด 2025-12-08 17:26:30
 JavaScript Tutorial
 2025-12-08 09:40:29
 แชร์หน้านี้:  

ข่าวบันเทิง