0
0
JavascriptHow-ToBeginner · 3 min read

How to Get Current Timestamp in JavaScript Quickly

To get the current timestamp in JavaScript, use Date.now() which returns the number of milliseconds since January 1, 1970. Alternatively, you can use new Date().getTime() for the same result.
📐

Syntax

The main ways to get the current timestamp are:

  • Date.now(): Returns the current time in milliseconds since January 1, 1970 (Unix epoch).
  • new Date().getTime(): Creates a new Date object for the current time and gets its timestamp in milliseconds.
javascript
Date.now()

new Date().getTime()
💻

Example

This example shows how to get and print the current timestamp using both methods.

javascript
const timestamp1 = Date.now();
const timestamp2 = new Date().getTime();

console.log('Timestamp using Date.now():', timestamp1);
console.log('Timestamp using new Date().getTime():', timestamp2);
Output
Timestamp using Date.now(): 1685664000000 Timestamp using new Date().getTime(): 1685664000000
⚠️

Common Pitfalls

Some common mistakes when getting the current timestamp:

  • Using new Date() alone without .getTime() returns a Date object, not a number.
  • Confusing seconds and milliseconds: JavaScript timestamps are in milliseconds, so dividing by 1000 is needed to get seconds.
  • Using Date.parse() without arguments returns NaN, not the current timestamp.
javascript
/* Wrong: returns Date object, not timestamp */
const wrong = new Date();
console.log(typeof wrong); // "object"

/* Right: get timestamp number */
const right = new Date().getTime();
console.log(typeof right); // "number"
Output
object number
📊

Quick Reference

MethodDescriptionReturns
Date.now()Current timestamp in millisecondsNumber (milliseconds)
new Date().getTime()Timestamp from current Date objectNumber (milliseconds)
new Date()Current date and time objectDate object

Key Takeaways

Use Date.now() for a quick current timestamp in milliseconds.
new Date().getTime() also returns the current timestamp as a number.
JavaScript timestamps count milliseconds since January 1, 1970.
Avoid using new Date() alone when you need a timestamp number.
Remember to convert milliseconds to seconds if needed by dividing by 1000.