JavaScript Program to Show Date and Timestamp

JavaScript Program to Show Date and Timestamp

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.

    // 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.

<!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>

 

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post