122 of 264 menu

Date object

The Date object is the main object for working with dates.

Syntax

let date = new Date();

Now the variable date is an object with a date that stores the current time (second, minute, hour, and so on). With the help of special functions, we can get the time characteristics 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.getSeconds()); // seconds console.log(date.getMinutes()); // minutes console.log(date.getHours()); // hours console.log(date.getDate()); // days console.log(date.getMonth()); // months from zero console.log(date.getFullYear()); // year console.log(date.getDay()); // current day of the week

Setting a specific point in time

You can set not the current moment of time, but the given one. To do this, pass parameters in the format new Date(year, month, day, hours, minutes, seconds, milliseconds), and in this case, the variable date will not be written into the current time, but into the one that we specified in the parameters. Features of this format: the countdown of months starts from zero, the missing parameters, starting from hours, are considered equal to zero, and for the year, months and days - one.

Example

Let's display the current day, month and year in the format 'year-month-day' (the month will be 1 less than the present one, since month numbering from zero):

let date = new Date(); let str = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate(); console.log(str);

See also

byenru