How to Get the Current Timestamp in JavaScript

Updated onbyAlan Morel
How to Get the Current Timestamp in JavaScript

Time and dates are important concepts to work with in any programming language, and JavaScript is no exception.

One of the most useful formats for time is the UNIX timestamp.

In this post, we will look at how to get the current timestamp in JavaScript.

What is a UNIX timestamp?

Before we look at how to get the current timestamp in JavaScript, let’s first look at what a UNIX timestamp is.

A UNIX timestamp is a number that represents the number of seconds that have passed since January 1st, 1970 at 00:00:00 UTC.

This means that the UNIX timestamp is a way to represent a point in time.

How to get the current timestamp in JavaScript

There are a few ways to get the current timestamp in JavaScript.

The most common way to accomplish this is to use the built-in Date object.

The Date object is a built-in object in JavaScript that represents a single moment in time.

To get the current timestamp, we can use the now() method.

JAVASCRIPT
const timestamp = Date.now();

Alternatively, you can use the getTime() method.

JAVASCRIPT
const timestamp = new Date().getTime();

Remember that this returns the UNIX timestamp in milliseconds, so you will need to divide it by 1000 to get the timestamp in seconds.

JAVASCRIPT
const seconds = new Date().getTime() / 1000;

From this, you can now store this data in a database or use it in any other way you want.

Conclusion

In this post, we learned how to get the current timestamp in JavaScript.

You can use the Date object to get the current timestamp and call the now() or getTime() method.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.