To get the current timestamp in JavaScript, you can use the Date.now(), new Date.getTime() , or new Date.valueOf() methods.
Method 1: Date.now()
The Date.now method is used to return the number of milliseconds elapsed since the epoch, defined as midnight on January 1, 1970, UTC.
Visual Representation
Example
let timestamp = Date.now();
console.log(timestamp);
Output
1702012836396
Converting to Seconds
If you require the timestamp in seconds , you can divide the milliseconds by 1000 and round it.
Example
let timestampInSeconds = Math.floor(Date.now() / 1000);
console.log(timestampInSeconds);
Output
1702012836
Method 2: new Date.getTime()
You can create a new Date object and use the getTime() method, which also returns the timestamp in milliseconds.
Visual Representation
Example
let timestamp = new Date().getTime();
console.log(timestamp);
let timestampInSeconds = new Date().getTime();
console.log(Math.floor(timestampInSeconds / 1000)); //timestamp in seconds
Output
1702012933591
1702012933
Method 3: new Date.valueOf()
The valueOf() method essentially does the same thing as getTime().
Visual Representation
Example
let timestamp = new Date().valueOf();
console.log(timestamp);
let timestampInSeconds = new Date().valueOf();
console.log(Math.floor(timestampInSeconds / 1000)); //timestamp in seconds
Output
1702013560439
1702013560
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.