timestamp
javascript

How do I get a timestamp in JavaScript?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In JavaScript, you can get the current timestamp in several ways, depending on what you need. Here are the most common methods:

1. Using Date.now()

The simplest way to get the current timestamp in milliseconds since the Unix epoch (January 1, 1970) is by using Date.now():

javascript
const timestamp = Date.now();
console.log(timestamp); // Example output: 1629384965090
  • Date.now() returns the number of milliseconds that have elapsed since January 1, 1970, 00:00:00 UTC.

2. Using new Date().getTime()

Another way to get the timestamp is by creating a new Date object and calling the getTime() method:

javascript
const timestamp = new Date().getTime();
console.log(timestamp); // Example output: 1629384965090
  • new Date().getTime() provides the same result as Date.now(), giving you the current timestamp in milliseconds.

3. Using new Date().valueOf()

You can also use the valueOf() method, which returns the primitive value of the Date object, which is the same as the timestamp in milliseconds:

javascript
const timestamp = new Date().valueOf();
console.log(timestamp); // Example output: 1629384965090

4. Using +new Date()

You can get the timestamp by using the unary plus (+) operator with a Date object, which converts the Date object into a number (milliseconds since the Unix epoch):

javascript
const timestamp = +new Date();
console.log(timestamp); // Example output: 1629384965090

5. Getting a Timestamp in Seconds

If you need the timestamp in seconds (instead of milliseconds), you can divide the result by 1000 and use Math.floor() to remove the decimal part:

javascript
const timestampInSeconds = Math.floor(Date.now() / 1000);
console.log(timestampInSeconds); // Example output: 1629384965

Summary

  • Date.now(): The most straightforward way to get the current timestamp in milliseconds.
  • new Date().getTime(): Another way to get the current timestamp in milliseconds.
  • +new Date(): A concise alternative to get the timestamp in milliseconds.
  • Seconds: Use Math.floor(Date.now() / 1000) for a timestamp in seconds.

All these methods give you the current timestamp, and you can choose the one that best fits your coding style or specific needs.


Course illustration
Course illustration

All Rights Reserved.