ตัวอย่างโค้ด
ใช้ toLocaleDateString() จัดรูปแบบวันที่ตาม locale
function changeDateFormat(dateValues, addToFront = "") {
return typeof dateValues == "object" ? addToFront + dateValues.toLocaleDateString() : "";
}
var currentDate = new Date();
console.log("The current date values=" + currentDate);
console.log("After formatting date values=" + changeDateFormat(currentDate));รันด้วยคำสั่ง:
node fileName.js
ชื่อไฟล์: demo289.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo289.js The current date values=Sat Aug 29 2020 12:51:06 GMT+0530 (India Standard Time) After formatting date values=8/29/2020
คำอธิบาย: toLocaleDateString() คืนค่าวันตาม locale ของระบบ (ตัวอย่างเป็น en-US รูปแบบ M/D/YYYY) สามารถระบุ locale และ options ได้ เช่น toLocaleDateString('th-TH') หรือ {year: 'numeric', month: 'long', day: 'numeric'}