Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เอกสารการจัดรูปแบบวันที่ (Date Formatting) ใน JavaScript อยู่ที่ไหน

Date Object เป็น Built-in Datatype ของ JavaScript สร้างด้วย new Date() หลายรูปแบบ

Constructor Patterns

new Date()                           // ปัจจุบัน
new Date(milliseconds)               // Unix timestamp (ms since 1970)
new Date(dateString)                 // Parse ISO 8601 / RFC 2822 string
new Date(year, monthIndex, day, hours, minutes, seconds, ms)
// monthIndex: 0=Jan, 11=Dec

เมธอด Get (Local Time)

Methodคำอธิบาย
getDate()วัน (1-31)
getDay()วันในสัปดาห์ (0-6, 0=Sun)
getFullYear()ปี (4 หลัก)
getHours()ชั่วโมง (0-23)
getMilliseconds()มิลลิวินาที (0-999)
getMinutes()นาที (0-59)
getMonth()เดือน (0-11)
getSeconds()วินาที (0-59)
getTime()Timestamp (ms since epoch)
getTimezoneOffset()Offset จาก UTC (นาที)

เมธอด Format (สำคัญ)

MethodOutput Exampleใช้เมื่อไหร่
toISOString()2024-01-15T10:30:00.000ZAPI, Database, Storage (UTC, Standard)
toLocaleString()15/1/2024, 17:30:00แสดงผล User (Local, Locale-aware)
toLocaleDateString()15/1/2024แสดงแค่วันที่
toLocaleTimeString()17:30:00แสดงแค่เวลา
toString()Mon Jan 15 2024 17:30:00 GMT+0700Debug/Log
toUTCString()Mon, 15 Jan 2024 10:30:00 GMTHTTP Headers, Legacy

Intl.DateTimeFormat (ทันสมัย, แนะนำ)

const date = new Date();

// Thai Locale
new Intl.DateTimeFormat('th-TH', {
  year: 'numeric', month: 'long', day: 'numeric',
  hour: '2-digit', minute: '2-digit'
}).format(date); // "15 มกราคม 2567, 17:30"

// Custom Format with formatToParts
const fmt = new Intl.DateTimeFormat('en-US', {
  year: 'numeric', month: '2-digit', day: '2-digit'
});
fmt.formatToParts(date).map(p => p.value).join('/'); // "01/15/2024"

เอกสารอ้างอิงอย่างเป็นทางการ

แนะนำ Library: date-fns (Modular, Tree-shakable), Luxon (Rich API, Timezone), Day.js (Lightweight, Moment.js API)