This is a simple JavaScript Program to show Date and Time Stamp on a webpage. In this script we define a JavaScript function named getFormattedDateTime
. This function uses the Date
object to get the current date and time. It then formats them into a human-readable string.
The we define event listener that waits for the HTML document to be fully loaded before executing the provided function. Inside the event listener function, we call getFormattedDateTime
to get the formatted date and time. Then, we create a new paragraph element (<p>
) using document.createElement('p')
. We set the text content of this paragraph to include the message “Page loaded on:” followed by the formatted date and time. Finally, we append this paragraph element to the body of the HTML document.
Many people confuse about JavaScript array[] and object{}, so this tutorial will explain the difference in between JavaScript {} and []. Arrays are ordered collections of values while Objects are collections of key-value pairs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // Function to format the date and time function getFormattedDateTime() { const now = new Date(); const date = now.toDateString(); const time = now.toLocaleTimeString(); return `${date} ${time}`; } // Display date and time stamp on the page document.addEventListener('DOMContentLoaded', function() { const dateTimeStamp = getFormattedDateTime(); const timestampElement = document.createElement('p'); timestampElement.textContent = `Page loaded on: ${dateTimeStamp}`; document.body.appendChild(timestampElement); }); |
You can define the basic structure of an HTML document as below. It includes a title and sets up the document’s body.
1 2 3 4 5 6 7 8 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Date and Time Stamp</title> </head> <body> |