Write a JavaScript Program to Display Date and Time

As a JavaScript programmer, one of the fundamental things to learn is how to display the date and time on a web page.

This skill comes in handy when creating applications that require time tracking or event scheduling.

In this article, we will be exploring how to display the current date and time using JavaScript.

To display the date and time, we will be making use of the built-in JavaScript Date object.

The Date object provides various methods that enable us to retrieve different parts of the current date and time.

To get started, let’s create a simple HTML file that will serve as our container.

Open your preferred text editor and create a new HTML file with the following code:

<!DOCTYPE html>
    <title>Display Date and Time using JavaScript</title>
    <h1>Date and Time</h1>
    <p id="datetime"></p>
    <script src="script.js"></script>

In the code above, we have created a basic HTML file that contains a title, a header, and a paragraph tag with an ID of “datetime.” We have also linked a JavaScript file called “script.js” to the HTML file.

Next, let’s open the “script.js” file and add the following code:

// Get the paragraph element with an ID of "datetime"
const datetimeElement = document.getElementById("datetime");

// Create a new Date object
const currentDatetime = new Date();

// Display the current date and time in the "datetime" paragraph element
datetimeElement.textContent = currentDatetime.toLocaleString();

In the code above, we first retrieved the paragraph element with an ID of “datetime” using the document.getElementById() method. We then created a new Date object using the “new Date()” constructor.

Finally, we displayed the current date and time in the “datetime” paragraph element using the toLocaleString() method of the Date object.

The toLocaleString() method formats the date and time based on the user’s local settings.

Save the “script.js” file and refresh the HTML page in your browser. You should now see the current date and time displayed in the paragraph element.

In conclusion, displaying the current date and time using JavaScript is a simple task that requires the use of the built-in Date object.