Big white clock

How to get a Unix timestamp in JavaScript or TypeScript language

This is a detailed guide that explains how to get a Unix timestamp in either JavaScript or TypeScript programming language. We will provide samples that can be run in native environment, without usage of any 3rd party libraries. However, at the end of the article, you may see how to get a timestamp also with help of other libraries, such as Moment.js, Day.js and date-fns.

The solutions that we give below may be useful in various situations. For example, when you are making a NodeJS application and want to save timestamps in the database.

Native JavaScript methods to get a timestamp

You can get the desired value in just a single line. The Date class provides the static now() method. It returns a number of milliseconds since the Unix epoch. Please see the usage below:

const unixTimestamp = Date.now();

To get a value in seconds, you have to simply divide that value by 1000. See it in the code sample below:

const unixTimestampInSeconds = Date.now() / 1000;

If you need to get a number of seconds in multiple places of your application, then you can make a special function for that purpose. The example is given below. We get the number of milliseconds, divide by 1000 and then use the floor() method to round the value down.

function getUnixTimestamp() {
    return Math.floor(
        Date.now() / 1000
    )
}

You can adjust that function to your needs. It can be made as a part of a project that needs to work with the Unix timestamps.

Unary "+" sign operator

There is another unusual method that allows you to get a timestamp. It's the unary plus sign. If that symbol is added, the JavaScript will convert the object and produce an integer value. The usage is pretty straightforward and can be seen below:

const unixTimestamp = + new Date();

However, please keep in mind that the above method has a downside. It may work a little slower than the other solution due to the value conversion.

To get a value in seconds, you may want to divide it by 1000. Please see the example below.

const unixTimestampInSeconds = + new Date() / 1000;

getTime() method

You can call the getTime() method on an instance of the Date() class to get a timestamp. It will return a number of milliseconds that you can later use in your application.

As you can see below, we create a new object. Then we call the getTime() function to get the Unix timestamp.

const unixTimestamp = (new Date()).getTime();

Getting a number of seconds is an easy task as well. The same as we described earlier, you have to divide the value by 1000. Please see it below.

const unixTimestampInSeconds = (new Date()).getTime() / 1000;

valueOf() method

The Date() class also provides the valueOf() method. It can be used to get the number of milliseconds since the Unix epoch.

There is no difference to the way it works if compared to the getTime() method. However, the JavaScript language uses the valueOf() method internally. In most cases, it's called when an object is converted to a primitive. Also, it's worth mentioning that other objects in JavaScript also have the valueOf() method.

The following code shows how to get milliseconds with help of this function.

const unixTimestamp = new Date().valueOf();

You may also get the number of seconds by dividing that value by 1000, see it below.

const unixTimestampInSeconds = new Date().valueOf() / 1000;

How to get timestamp in TypeScript

If you are building a TypeScript project, then you may want to create an object oriented version of the code that gets the timestamp.

Following is our example of a very basic class that contains two static methods. First one is the "getTimestamp()" method, which returns a number of milliseconds since the Unix epoch. The other one is the "getTimestampInSeconds()" method, it produces a value in seconds.

class DateUtils {
    public static getTimestamp() {
        return Date.now();
    }

    public static getTimestampInSeconds() {
        return Math.floor(
            Date.now() / 1000
        );
    }
}

Now, we can test how that new TypeScript class works. You may run the code below and see the output in the browser console.

console.log(DateUtils.getTimestamp());
console.log(DateUtils.getTimestampInSeconds());

Converting timestamp back to the Date class

In this guide, we've already shown many examples on how to get a timestamp. But you may want to know how to convert the timestamp back to the Date() object.

That's a very simple operation and requires just a single line of code. The number of milliseconds must be passed as an argument into the constructor of the Date() object. Please see our example below:

const convertedDate = new Date(unixTimestamp);

After that, you can try to print the time to the console with help of the toDateString() method.

console.log(convertedDate.toDateString());

The output may be like the following:

Thu Dec 01 2022

Timestamp for a given date

You may also get a Unix timestamp for a specific date. You have to pass the desired value as an argument into the constructor of the Date() class.

The usage is very simple, please review our code sample below. It will return a number of milliseconds for the "2022-11-10" date.

const unixTimestamp = (new Date("2022-11-10")).getTime();

To get seconds for the same date, you have to divide the returned value by 1000. Following is our example.

const unixTimestampInSeconds = (new Date("2022-11-10")).getTime() / 1000;

The Date() class can accept dates in various formats. In the code below, we pass year, month and day values as integers.

const unixTimestamp = (new Date(2022, 11, 10)).getTime();

It's also possible to specify hours, mints and seconds. That will allow getting a more precise timestamp.

const unixTimestamp = (new Date(2022, 11, 10, 8, 10, 0)).getTime();

Moment.js library

You may decide to use a separate library in your application for manipulating the dates. Perfect example is the Moment.js library. It provides a wide range of various helpful methods. In case you decide to use it, getting a timestamp is a quick task there as well.

For example, to get a number of seconds since the Unix epoch, you may do the following:

moment().unix();

Also, to get a number of milliseconds you can use the valueOf() method of the moment() instance.

moment().valueOf();

Lodash library

If you are building a Lodash application, then getting a timestamp there is not an issue as well. Please review the following code example.

var _ = require('lodash');

const unixTimestamp = _.now();

As you see, the Lodash library provides the now() method. If called, it returns a number of milliseconds since the Unix epoch.

Getting a number of seconds is a simple task there. We've already shown that earlier in this article. However, in case you just directly jumped into this section and don't want to scroll, here is the code.

var _ = require('lodash');

const unixTimestampInSeconds = _.now() / 1000;

Day.js library

Days.js is a very small library that allows you to parse and manipulate dates in your JavaScript application. It also contains methods that can return a timestamp.

The usage is simple. You have to instantiate the "dayjs" class and then call the valueOf() method. The returned value will contain number of milliseconds, please see the code sample below:

const unixTimestamp = dayjs().valueOf();

You may also use the unary "+" operator to get the timestamp. It should be called with the instance of the "dayjs" class. The result will be in milliseconds, please see the code below.

const unixTimestamp = +dayjs();

To get a number of seconds you may call the unix() method. Our example is given below:

const unixTimestampInSeconds = dayjs().unix();

date-fns library

If you are using the "date-fns" library in your project, then you can get a Unix timestamp as well. The main difference is that this library is modular and uses native JavaScript Date class.

It means that you have to instantiate the time object by calling the new Date() code. And after that, you can call the getTime() function which will return a timestamp in milliseconds. Please see our code sample below.

const unixTimestamp = getTime(new Date());

Also, you can get seconds as well. There is no need to divide the result by 1000. You have to call the getUnixTime() function which will return the result in seconds.

const unixTimestampInSeconds = getUnixTime(new Date());

Additional notes

It is worth mentioning that there are many other useful JavaScript libraries that can work with the dates. We've described only the popular tools. However, you may find additional nice libraries in the official "npmjs" repository. Also, you may try to search for JavaScript or TypeScript projects directly on the github.com web site.

Conclusion

As you see, it's very easy to get a Unix timestamp in either JavaScript or TypeScript language. Also, It is probably one of the most popular tasks that the developer may need to do when making a code for the web.

There are so many applications that use the time values for various purposes. And it's important to know how to make it correctly. Even such a simple task as getting a timestamp may have side effects.

For example, calling the static Date.now() function may work faster. But instantiating an object and using the getTime() method may work a little slower. Other 3rd party libraries may work differently. If you are building a time-critical application, you can measure execution time for each method and find the most applicable solution.

Related Articles

Man typing on laptop

How to send AJAX request in the WordPress

Html source code

How to change a CSS class in JavaScript

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *