Skip to content

02: Displaying Dates with Javascript

martin@mustbebuilt.co.uk edited this page Nov 14, 2024 · 1 revision

The document is not the only object available to Javascript developers, there are many more. A good one to experiment with is the Date object. We'll be able to use this to display the current date and time.

To create a new Date object we instantiate it. This is done with the new keyword eg:

const myDate = new Date();

To view what this has done add the following to your code:

console.dir(myDate);

When viewing the output in the console you will see:

Date Object in the console

As the above demonstrates there are a large number of methods related to the Date object. The toDateString() methods returns just the date part of the object.

Add the current date to the DOM via the node we created above.

myNode.innerHTML = myDate.toDateString();

Save and test your file. You should see the date displayed.

Displaying the Time

To display the time rather than the date change toDateString to toTimeString. However, this gives us more details than we require as we just want the time in 00:00:00 format. We use the toLocaleTimeString method of the Date object to achieve this.

// show only hours, minutes and seconds
myNode.innerHTML = myDate.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit", second: "2-digit" });

Alternatively, you could use { timeStyle: "medium" } to specifiy the formatting options. The "medium" style displays the time in the same format, including hours, minutes, and seconds.

// show only hours, minutes and seconds
myNode.innerHTML = myDate.toLocaleTimeString("en-GB", { timeStyle: "medium" });

See MDN_web_docs for more options for displaying time.

Clone this wiki locally