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

วิธีหาวินาทีนับจาก Epoch ใน JavaScript

ใช้ Date.getTime() หาร 1000 แล้วปัดเศษด้วย Math.round()

ไวยากรณ์

var anyVariableName = new Date();
Math.round(yourDateVariableName.getTime() / 1000);

ตัวอย่างโค้ด

var currentDate = new Date();
var epochSeconds = Math.round(currentDate.getTime() / 1000);
console.log(epochSeconds);

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo67.js)

ผลลัพธ์ตัวอย่าง

1594821507