How to Get Current Date and Time in JavaScript

If you want to include the current date or time or both into your application and you are looking for a way to get them in javascript, this article will explain two solutions on how to get the date and time in javascript. The first solution uses the date() object, and the second uses the external library Moment.js.

Related Articles:

1. Getting current date in javascript

1.1. Get current date using Date() object

The Date() is a built-in JavaScript object that handles all operations related to the date and time. It is generally used to display the user’s current time and date, build timers, etc.

1.1.1 Get current date using Date() methods

JavaScript provides various methods that operate on the Date object. These methods are used to extract and get specific information about the date and time and then display them in a readable way ( year, month, day, hour, minute, second, and millisecond)

Here’s an example of how you can use the Date() object:

 const today = new Date();
 console.log(today);  //  this will print the current date and time

You can also use the method getFullYear() of the Date object to get the current year.

 const today = new Date();
const year = today.getFullYear();
console.log(year);  // this will  print the current year

The method getMonth()  returns the month as a number from [0, 11], which means the number 0 represents Jan, and the number 11 represents Dec, so to get the correct current month value, we add 1.

 
 const today = new Date();
const month = today.getMonth() + 1;
console.log(month);  // this will  print the current month

To get the day as a number from [1, 31], we use the method getDate() as follows:

 
 const today = new Date();
const day = today.getDate();
console.log(day);  // this will  print the current day

Now we can arrange these results values in the format we want:

 
 const today = new Date();
 const year = today.getFullYear();
 const month = today.getMonth() + 1;
 const day = today.getDate();
 const Date = `${day}-${month}-${year}`;
 console.log(Date);  
  //or
  const Date = `${day}/${month}/${year}`;
 console.log(Date);  

1.1.2 Get current Local date using toLocaleDateString()

The toLocaleDateString() is a simple method that returns the current date in a specific format based on the user’s locale settings and languages by accepting an argument to specify the location (country).

For example, to get the current date in Korea, we use the following code:

  // Korean uses year-month-day order
 const date = date.toLocaleDateString("ko-KR");
  console.log(date);  // this will print "2023. 01. 20."

1.1.3 Get current date using Moment.js library

Moment.js is a free JavaScript date library for parsing, validating, manipulating, and formatting dates. We can use Moment.js to display the current date in different formats.

To use this library, you have to install it first:

  npm install moment --save

Here are some examples of how to use Moment.js

   const dateTime = moment().format('MMMM Do YYYY, h:mm:ss a'); 
   console.log(dateTime); // January 6th 2023, 4:42:31 pm
   
    const day= moment().format('dddd');   
    console.log(day)  // Friday

   const date = moment().format("MMM Do YY");
    console.log(date) // Jan 6th 23
                       

Keep in mind that installing an external library for just one operation is not recommended. But if you already have Moment.js installed on your project, go ahead and use it.

2. Getting current time in JavaScript

2.1 What is timestamp

The UNIX timestamp is defined as the number of milliseconds since January 1, 1970, UTC. To get the current timestamp in JavaScript, you use the getTime() method of the Date object as follows:

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

Remember that this will give you the current time in the number of milliseconds since January 1, 1970. If you need the number of seconds, you’ll need to divide the result by 1000.

 
 const currentTime = new Date().getTime();
 const currentTimeInSeconds = Math.floor(currentTime / 1000);

2.2. Get current time using Date() object

2.2.1 Get current time using Date methods

As we already mentioned, the Date object has various methods that can be useful to get the current time in a specific format.

  • getHours(): this method provides the current hour between 0-23.
 const currentTime = new Date();
 const hours = currentTime.getHours();
 
  • getMinutes(): to get the current minutes, we use the getMinutes() method. This method will return a value between 0-59.
  const currentTime = new Date();
  const minutes = currentTime.getMinutes();
  
 
  • getSeconds(): this method returns the current seconds between 0-59.
  const currentTime = new Date();
  const seconds = currentTime.getSeconds();
 

For example, to get the current time in the format “HH:MM:SS”, we use the following code:

 
 const currentTime = new Date();
 const hours = currentTime.getHours();
 const minutes = currentTime.getMinutes();
 const seconds = currentTime.getSeconds();
 const time = `${hours}:${minutes}:${seconds}`;
 
 

2.2.2 Get current Local time using toLocaleTimeString()

The toLocaleTimeString() is a method that returns the current time in a specific format based on the user’s locale settings and languages by accepting an argument to specify the location (country).

Here are some examples:

 
 // British English uses 24-hour time without AM/PM
 console.log(date.toLocaleTimeString("en-GB")); // this will print "23:05:00"
 
 // US English uses 12-hour time with AM/PM
 console.log(date.toLocaleTimeString("en-US")); // this will print "11:05:00 PM"


2.2.3 Get current time using Moment.js library

As we already said, Moment.js is a free JavaScript date library for parsing, validating, manipulating, and formatting dates. We can use Moment.js to display the current Time in the wanted format.

In order to use this library, you have to install it first:

  npm install moment --save

Here are some examples of how to use Moment.js to get the current time:

   
  const timeLT = moment().format('LT');   
  console.log(timeLT); // 5:12 PM

  const timeLTS= moment().format('LTS'); 
  console.log(timeLTS); // 5:12:25 PM

                       

Conclusion

This article explained different ways to get the date and time in Javascript using the Date object and its methods. We also showed you how to do it using an external library, Moment.js. I hope this was helpful!

You might also like:

How to add Custom Error Handler Middleware to your Node.js/Express API.

Complete JWT Authentication and Authorization System for MySQL/Node.js API.

How to Build a Complete API for User Login and Authentication using MySQL and Node.js.

Node.js + MySQL : Add Forgot/Reset Password to Login-Authentication System.

Nodemailer + Gmail: How to Send Emails from Node.js API using Gmail.

How to store Session in MySQL Database using express-mysql-session.

How to interact with MySQL database using async/await promises in node.js ?

How to use Sequelize async/await to interact with MySQL database in Node.js.

MANY-TO-MANY Association in MYSQL Database using Sequelize async/await with Node.js.

ONE-TO-ONE Association in MYSQL Database using Sequelize async/await with Node.js

ONE-TO-ONE Association in MYSQL Database using Sequelize async/await with Node.js.

How to add Routes to insert data into MySQL database-related tables in Node.js API?

Example How to use initialize() Function in Node.js/Express API .

Why is Connection Pooling better than Single Connection?.

How to create MySQL database using node.js.

Leave a Comment

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

Translate »