How to Get Current Timestamp in JavaScript

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

Visual Representation of Date.now()

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

Visual Representation of Date.getTime()

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

Visual Representation of new Date.valueOf()

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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.