How to Get Current Time and Date Using JavaScript Date Object

Date object is pretty useful. Often, you have to use it If you use JavaScript. Not only current time and date, but also we can do more than that using this object. But I am not going to write all of them.

First of all, we have to create this object from the new Date() class. After instantiating this, we will get a date object. If we don’t pass anything when instantiating the class. We will get the current time and date details in the date object. You can see what it prints in your console by running the following code.

const date = new Date();

Most of the time, we don’t need the complete details. We need specific data. Suppose we need the current year, month, time, etc. For that, we can easily use this object’s methods. Let’s see some of them.

See the following code for getting the output of the day, month, year.

const date = new Date();
const currDate = date.getDate();
const month = date.getMonth();
const year = date.getFullYear();

console.log(month, currDate, year);

Here month’s count starts from zero. Suppose for January it will give 0 and for December 11.

See the following code for getting the output of the weekday, hour, minutes, seconds.

const date = new Date();
const weekDay = date.getDay();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();

One thing to keep in mind, in this case, we only get the time of that moment when the date object is created. If we call its methods one hour after the script is run or the date object is created, then it will give us one hour ago’s time.

To solve this problem, we can use the setTimeout() method. Using this method, we can call a function continuously after a certain time. To more about this window method, click here. There is a nice example of this method by the example of creating a clock.

That’s it for this blog. I hope you like it.

Scroll to Top