Monday, 28 October 2024

How to Get a Timestamp in JavaScript: A Complete Guide

In JavaScript, getting the current timestamp—a numeric representation of the current date and time—is straightforward but offers flexibility based on the desired precision and compatibility. This guide will walk you through methods to get a timestamp, both in milliseconds (common in JavaScript) and seconds (standard in Unix and often preferred in cross-language contexts).

1. Getting the Timestamp in Milliseconds

JavaScript has a built-in method for fetching the current timestamp in milliseconds: Date.now(). This is a simple and modern way to get the time since the Unix epoch (January 1, 1970, at midnight UTC):

let timestampMs = Date.now();
console.log(timestampMs); // e.g., 1632159274427

If you prefer alternatives, you can get the same result by creating a new Date object and calling .getTime():

let timestampMs = new Date().getTime();
console.log(timestampMs); // e.g., 1632159274427

Or, for a shorter syntax, use the unary + operator with new Date():

let timestampMs = +new Date();
console.log(timestampMs);
Read more »

Labels: