Get the Current Timestamp in NodeJS – Multiple Easy Methods

Node.js can use a Date object that provides information about a timestamp. This object can be used for various purposes such as getting the current time, comparing dates, formatting dates, reminders, etc.

Date objects represent a specific point in time and are independent of the platform they are being used on. The date and time returned from this object can be stored to maintain a record such as when a user posts an article, when a message is viewed, etc.

This tutorial will provide a comprehensive guide on how to get timestamps in Node.js. We will discuss the different forms of timestamps that we can obtain in Node.js.

Points we cover:

  • Understand how to obtain the current date, month, year, hour, minutes, and seconds in Node.js.
  • Understand how to obtain the current date-time formatted in YYYY-MM-DD hh:mm:ss, YYYY-MM-DD, DD-MM-YYYY, and so on.
  • Understand how to obtain the current timestamp.
  • Understand how to calculate the date and time from a given timestamp.

The Date object used to handle date and time in Node.js is built-in, i.e. it is globally available and does not require module import.

Getting Current Date and Time in NodeJS in YYYY-MM-DD hh:mm:ss Format

The current date and time can be fetched by first creating a new Date object. The date object returns the number of milliseconds elapsed since Jan 1, 1970, 00:00:00 UTC. This is often referred to as the Unix epoch or the POSIX time.

// new Date object
const dateObject = new Date();

The date object has various methods used to get data and time in different formats, some of them are:

  • getDate – returns the month’s day (1-31)
  • getMonth – this function returns the month as an integer (0-11). It is worth noting that January is represented as 0 and December as 11.
  • getFullYear – returns the year in four digits.
  • getHours – returns the current time in 24-hour format (0-23)
  • getMinutes – returns the current minute (0-59)
  • getSeconds – returns the number of seconds (0-59)

Using the methods described above, one can create the date and time in the YYYY-MM-DD hh:mm:ss format. Although some methods return single-digit values, we must append 0 before them (for example “6” becomes “06”).

Below is an example of how to get the current date and time in YYYY-MM-DD hh:mm:ss format using the methods specified above:

const dateObject = new Date();
// current date
// adjust 0 before single digit date
const date = (`0 ${dateObject.getDate()}`).slice(-2);

// current month
const month = (`0 ${dateObject.getMonth() + 1}`).slice(-2);

// current year
const year = dateObject.getFullYear();

// current hours
const hours = dateObject.getHours();

// current minutes
const minutes = dateObject.getMinutes();

// current seconds
const seconds = dateObject.getSeconds();

// prints date in YYYY-MM-DD format
console.log(`${year}-${month}-${date}`);

// prints date & time in YYYY-MM-DD HH:MM:SS format
console.log(`${year}-${month}-${date} ${hours}:${minutes}:${seconds}`);

// prints time in HH:MM format
console.log(`${hours}:${minutes}`);

Output:

2021-11-28
2021-11-28 1:26:5
1:26

Getting Current Timestamps

The Date.now() method can be used to obtain the timestamp. It is important to keep in mind that this method returns the timestamp in milliseconds. We can divide the timestamp by 1000 to get the timestamp in seconds.

const timestamp = Date.now();

// timestamp in milliseconds
console.log(timestamp);

// timestamp in seconds
console.log(Math.floor(timestamp/1000));

Output:

1638043140212
1638043140

Getting Date and Time from Timestamp

The timestamp is passed as a parameter to the Date constructor in order to get the date and time values from it. Because JavaScript timestamps are specified in milliseconds, if the given timestamp is in seconds, you must convert it to milliseconds by multiplying it by 1000.

// current timestamp in milliseconds
const timestamp = Date.now();

const dateObject = new Date(timestamp);
const date = dateObject.getDate();
const month = dateObject.getMonth() + 1;
const year = dateObject.getFullYear();

// prints date & time in YYYY-MM-DD format
console.log(`${year}-${month}-${date}`);

Output:

2021-11-28

Perfect! The codes have turned out great and we have successfully drawn all the right data and time formats.

Also Read: How to Check If a Date Is Today in JavaScript

Conclusion

In this tutorial, we have learned how to get timestamp in JavaScript and Node. We have also discussed how we can retrieve the different formats of the timestamp. Getting the time and date is the most essential part of developing any JS application as the time needs to be stored at many stages, such as for social media websites, when a message is sent, when it is received, when a user post something, when someone comments, etc. Hope you find this tutorial helpful.

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

Aneesha S
Aneesha S
Articles: 171