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

ฟังก์ชัน Date.toLocaleDateString() ใน JavaScript

ฟังก์ชัน toLocaleDateString() ของออบเจกต์ Date คืนค่า ส่วนของวันที่ (ไม่รวมเวลา) ตามรูปแบบ locale ของผู้ใช้

ไวยากรณ์

dateObj.toLocaleDateString([locales[, options]])

ตัวอย่าง

<html> <head>    <title>JavaScript Example</title> </head> <body>    <script type="text/javascript">       var dateObj = new Date('September 26, 89 12:4:25:96');       document.write("วันที่ปัจจุบัน: "+dateObj.toLocaleDateString());    </script> </body> </html>

ผลลัพธ์

วันที่ปัจจุบัน: 9/26/1989

ตัวอย่าง: ใช้วันที่ปัจจุบัน

<html> <head>    <title>JavaScript Example</title> </head> <body>    <script type="text/javascript">       var dateObj = new Date();       document.write("วันที่ปัจจุบัน: "+dateObj.toLocaleDateString());    </script> </body> </html>

ผลลัพธ์

วันที่ปัจจุบัน: 18/10/2018

ตัวเลือก options สำหรับวันที่:

const options = {
  weekday: 'long',    // "Monday"
  year: 'numeric',    // "2024"
  month: 'long',      // "January"
  day: 'numeric'      // "15"
};
date.toLocaleDateString('th-TH', options); // "วันจันทร์ที่ 15 มกราคม 2567"

รูปแบบ month ที่ใช้ได้:

  • numeric: 1, 2, 3...
  • 2-digit: 01, 02, 03...
  • long: January, February...
  • short: Jan, Feb...
  • narrow: J, F, M...