สร้าง Date object แล้วใช้ getTime() / 1000
ตัวอย่างโค้ด
var currentDateTime = new Date();
console.log("The current date time is as follows:");
console.log(currentDateTime);
var resultInSeconds = currentDateTime.getTime() / 1000;
console.log("The current date time in seconds is as follows:");
console.log(resultInSeconds);รันด้วยคำสั่ง:
node fileName.js
ชื่อไฟล์: demo285.js
ผลลัพธ์
The current date time is as follows: 2020-08-28T16:13:35.987Z The current date time in seconds is as follows: 1598631215.987
คำอธิบาย: getTime() คืน milliseconds นับจาก Unix Epoch (Jan 1, 1970 UTC) หาร 1000 ได้วินาที (Unix timestamp) รวมทศนิยม milliseconds
การใช้งาน: ใช้สำหรับ timestamp API, cache expiration, คำนวณระยะเวลา