JavaScript dates

Author: MDBootstrap

JavaScript Date Object lets us work with dates:

                      <p id="example-1"></p>
                        var d = new Date();
                        document.getElementById("example-1").innerHTML = d;

Live preview

JavaScript Date Output

By default, JavaScript will use the browser's time zone and display a date as a full text string:

Live preview

new Date()

new Date() creates a new date object with the current date and time:

                    var d = new Date();

Note: Date objects are static. The computer time is ticking, but date objects are not.

new Date(year, month, ...)

new Date(year, month, ...) creates a new date object with a specified date and time.

7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):

                      var d = new Date(2018, 11, 24, 10, 33, 30, 0);

Live preview

Note: Note: JavaScript counts months from 0 to 11. January is 0. December is 11.

If you specify only 3 numbers you will display only year, month and day:

                    var d = new Date(2018, 11, 24);

Live preview

Exercises - test your knowledge

Exercise 1

Create a Date object and alert the current date and time.

                        var d = new Date();

Previous lesson Next lesson

Spread the word:
Do you need help? Use our support forum

About the author