Working with the Date object in JavaScript

Now we will start learning how to work with dates in JavaScript. To do this, we need the Date object, which can be used to manipulate dates in JavaScript.

Date object is created like this:

new Date();

Let's write the created object to some variable, for example, to the variable date:

let date = new Date();

After the operation, the variable date will be an object that stores the current moment of time (second, minute, hour, and so on).

Using this object and special methods, we can get the characteristics of time we need, for example, the current hour, current day or current month.

For example, the current hour can be obtained like this: date.getHours(), and the current month like this date.getMonth(). See all options:

let date = new Date(); console.log(date.getFullYear()); // a year console.log(date.getMonth()); // a month console.log(date.getDate()); // a day console.log(date.getHours()); // hours console.log(date.getMinutes()); // minutes console.log(date.getSeconds()); // seconds

Note that the month returned by the getMonth method starts from zero - January - zero, February - first, and so on.

Display the current day.

Display the current month.

Display the current year.

enru