Logo

How do I get a timestamp in JavaScript?

Quick and Easy Ways to Get the Current Timestamp in JavaScript

A timestamp is a numeric value representing a particular moment in time. In JavaScript, timestamps are commonly expressed as the number of milliseconds that have elapsed since the Unix epoch (January 1, 1970 00:00:00 UTC).

1. Using Date.now()

Date.now() returns the current time in milliseconds since the Unix epoch. This is the simplest and most direct approach:

const timestamp = Date.now(); console.log(timestamp); // e.g., 1669666875623

Key Points:

  • Introduced in ECMAScript 5, widely supported in modern environments.
  • Returns a number that represents the current time in milliseconds.

2. Using new Date().getTime()

Before Date.now() became standard, you could create a new Date object and call .getTime():

const timestamp = new Date().getTime(); console.log(timestamp);

Key Points:

  • Works in all browsers and older environments.
  • Slightly less efficient than Date.now() because it creates a new Date object before obtaining the time.

3. Using +new Date()

A handy shorthand technique is to use the unary plus operator on a new Date() object, which converts it to a number (the timestamp):

const timestamp = +new Date(); console.log(timestamp);

Key Points:

  • Concise and works in older browsers.
  • Less explicit than Date.now(), making the code slightly harder to read.

Which Method to Choose?

  • Use Date.now() for clarity, simplicity, and modern support.
  • Use new Date().getTime() or +new Date() if you need compatibility with very old browsers or prefer a single-line trick (though this is rarely necessary nowadays).

Strengthening Your JavaScript Fundamentals

Getting the current timestamp is a straightforward operation, but fully understanding how JavaScript works with dates, times, and different data types forms part of a robust JS foundation. For a comprehensive, beginner-friendly approach to all core JavaScript features:

  • Grokking JavaScript Fundamentals: A perfect course for beginners or those refining their skills, ensuring you understand not just date and time operations but the essentials of variables, arrays, objects, and more.

In Summary

To get the current timestamp in JavaScript:

  • Preferred: const timestamp = Date.now();
  • Alternative: const timestamp = new Date().getTime();
  • Shorthand: const timestamp = +new Date();

Choose the method that best fits your coding style and target environment.

TAGS
Java
JavaScript
CONTRIBUTOR
TechGrind